Share this blog!

Accessing a remote DB through SSH using JSch

The following sample shows an example code where JSch is used to create an SSH session and connect to a remote Database.

This sample Java project was created using maven and the mysql and JSch dependencies in the pom.xml are as follows:

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.54</version>
</dependency>

The connectSession() method will be creating a session and returning it (so it can be disconnected later).
The main method is simply accessing the DB using a typical database connection.

package com.sachi;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.sql.*;

/**
 * Created by Sachi on 4/1/2017.
 */
public class JschTrial {
    static int lport;
    static String rhost;
    static int rport;

    public static Session connectSession() {
        Session session = null;
        String user = "mySSHusername";       //ssh username
        String password = "mySSHpassword";   //ssh password
        String host = "myHOSTorIP";          //ssh host/IP
        int port = 22;
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(user, host, port);
            lport = 4321;
            rhost = "localhost";
            rport = 3306;
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            System.out.println("Establishing Connection...");
            session.connect();

            int assinged_port = session.setPortForwardingL(lport, rhost, rport);
            System.out.println("localhost:" + assinged_port + " -> " + rhost + ":" + rport);
        } catch (Exception e) {
            System.err.print(e);
        }
        return session;
    }

    public static void main(String[] args) {
        Session ses = null;
        try {
            ses = connectSession();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        System.out.println("An example for accessing remote db through ssh!");
        Connection con = null;
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://" + rhost + ":" + lport + "/";

        String db = "dabname";                //db name
        String dbUser = "root";               //db username
        String dbPasswd = "dbrootpassword";   //db userpassword
        try {
            Class.forName(driver);
            con = DriverManager.getConnection(url + db, dbUser, dbPasswd);
            try {
                String sql = "SELECT name FROM mytable";
                PreparedStatement ps = con.prepareStatement(sql);
                ResultSet rset = ps.executeQuery();
                while (rset.next()) {
                    System.out.println("Id : " + rset.getString("name"));
                }
            } catch (SQLException s) {
                System.out.println("SQL statement is not executed!");
            }
            con.close();
            ses.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Next PostNewer Post Previous PostOlder Post Home

0 comments:

Post a Comment