Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import com.jcraft.jsch.JSch;
- import com.jcraft.jsch.JSchException;
- import com.jcraft.jsch.Session;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.util.Properties;
- public class MySqlConnOverSSH {
- private static void doSshTunnel( String strSshUser, String strSshPassword, String strSshHost, int nSshPort, String strRemoteHost, int nLocalPort, int nRemotePort ) throws JSchException
- {
- final JSch jsch = new JSch();
- Session session = jsch.getSession( strSshUser, strSshHost, 22 );
- session.setPassword( strSshPassword );
- final Properties config = new Properties();
- config.put( "StrictHostKeyChecking", "no" );
- session.setConfig( config );
- session.connect();
- session.setPortForwardingL(nLocalPort, strRemoteHost, nRemotePort);
- }
- /**
- * Java Program to connect to remote database through SSH using port forwarding
- * @throws SQLException
- */
- public static void main(String[] args) throws SQLException {
- try
- {
- String strSshUser = "sshUserName"; // SSH loging username
- String strSshPassword = "sshPassWord"; // SSH login password
- String strSshHost = "10.20.0.234"; // hostname or ip or SSH server
- int nSshPort = 22; // remote SSH host port number
- String strRemoteHost = "db02"; // hostname or ip of your database server
- int nLocalPort = 3307; // local port number use to bind SSH tunnel
- int nRemotePort = 3306; // remote port number of your database
- String strDbUser = "dbUser"; // database loging username
- String strDbPassword = "dbUserPW"; // database login password
- MySqlConnOverSSH.doSshTunnel(strSshUser, strSshPassword, strSshHost, nSshPort, strRemoteHost, nLocalPort, nRemotePort);
- Class.forName("com.mysql.jdbc.Driver");
- Connection con = DriverManager.getConnection("jdbc:mysql://localhost:"+nLocalPort, strDbUser, strDbPassword);
- con.close();
- }
- catch( Exception e )
- {
- e.printStackTrace();
- }
- finally
- {
- System.exit(0);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement