Advertisement
Guest User

Untitled

a guest
Jul 25th, 2016
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. import com.jcraft.jsch.JSch;
  2. import com.jcraft.jsch.JSchException;
  3. import com.jcraft.jsch.Session;
  4.  
  5. import java.sql.Connection;
  6. import java.sql.DriverManager;
  7. import java.sql.SQLException;
  8. import java.util.Properties;
  9.  
  10. public class MySqlConnOverSSH {
  11. private static void doSshTunnel( String strSshUser, String strSshPassword, String strSshHost, int nSshPort, String strRemoteHost, int nLocalPort, int nRemotePort ) throws JSchException
  12. {
  13. final JSch jsch = new JSch();
  14. Session session = jsch.getSession( strSshUser, strSshHost, 22 );
  15. session.setPassword( strSshPassword );
  16.  
  17. final Properties config = new Properties();
  18. config.put( "StrictHostKeyChecking", "no" );
  19. session.setConfig( config );
  20. session.connect();
  21. session.setPortForwardingL(nLocalPort, strRemoteHost, nRemotePort);
  22. }
  23.  
  24. /**
  25. * Java Program to connect to remote database through SSH using port forwarding
  26. * @throws SQLException
  27. */
  28. public static void main(String[] args) throws SQLException {
  29. try
  30. {
  31. String strSshUser = "sshUserName"; // SSH loging username
  32. String strSshPassword = "sshPassWord"; // SSH login password
  33. String strSshHost = "10.20.0.234"; // hostname or ip or SSH server
  34. int nSshPort = 22; // remote SSH host port number
  35. String strRemoteHost = "db02"; // hostname or ip of your database server
  36. int nLocalPort = 3307; // local port number use to bind SSH tunnel
  37. int nRemotePort = 3306; // remote port number of your database
  38. String strDbUser = "dbUser"; // database loging username
  39. String strDbPassword = "dbUserPW"; // database login password
  40.  
  41. MySqlConnOverSSH.doSshTunnel(strSshUser, strSshPassword, strSshHost, nSshPort, strRemoteHost, nLocalPort, nRemotePort);
  42.  
  43. Class.forName("com.mysql.jdbc.Driver");
  44. Connection con = DriverManager.getConnection("jdbc:mysql://localhost:"+nLocalPort, strDbUser, strDbPassword);
  45. con.close();
  46. }
  47. catch( Exception e )
  48. {
  49. e.printStackTrace();
  50. }
  51. finally
  52. {
  53. System.exit(0);
  54. }
  55. }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement