Wednesday, February 29, 2012

Connect to Remote database through SSH using Port Forwarding with Java

Yesterday I need connect connect our remote MySQL database that was setup on SSH enabled server and query database. Since it was on SSH enabled server, we can’t connect it directly using JDBC connection API.To achieve this, we first need to create SSH session and then using Port Forwarding we can forward the request to server and connect to database. I used JSchJSch is a pure Java implementation of SSH2.

JSch allows you to connect to an sshd server and use port forwarding, X11 forwarding, file transfer, etc., and you can integrate its functionality into your own Java programs. JSch is licensed under BSD style license.

package com.handysofts.mysqlconnection;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

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

import java.sql.Connection;
import java.util.HashMap;

public class MySqlConnOverSSH {
    private Connection      dbConnAlfresco    = null;

    public static void main(String[] args) throws SQLException {
        int lport=3306;
        String host="";
        String rhost="";
        int rport=3306;
        String user="root";
        String password="#password#";
        String dbuserNameAlfresco = "dbuser";
        String dbpasswordAlfresco = "dbpass";
        String urlAlfresco = "jdbc:mysql://localhost:"+rport+"/alfresco?useUnicode=true&characterEncoding=UTF-8";
        String driverName="com.mysql.jdbc.Driver";
        Session session= null;
            //Set StrictHostKeyChecking property to no to avoid UnknownHostKey issue
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            JSch jsch = new JSch();
            session=jsch.getSession(user, host, 22);
            int assinged_port=session.setPortForwardingL(lport, rhost, rport);
            System.out.println("localhost:"+assinged_port+" -> "+rhost+":"+rport);
            System.out.println("Port Forwarded");
            //mysql database connectivity
            dbConnAlfresco  = DriverManager.getConnection (urlAlfresco, dbuserNameAlfresco, dbpasswordAlfresco);
            System.out.println ("Database connection established");

     String qnameSQL = "SELECT * FROM alf_node;";
     PreparedStatement prepStmnt = dbConnAlfresco.prepareStatement(qnameSQL);
     ResultSet rs = prepStmnt.executeQuery();
     while ({
      System.out.println("*** "+rs.getString("uuid")+" ***");

        }catch(Exception e){
            if(dbConnAlfresco != null && !dbConnAlfresco.isClosed()){
                System.out.println("Closing ALFRESCO Database Connection");
            if(session !=null && session.isConnected()){
                System.out.println("Closing SSH Connection");

NOTE: If connection fails then open task manager and kill your own mysql from active process and run again application.

1 comment:

  1. serve the different choices about remote dba specialists, remote dba administrations, remote dba bolster, remote database, prophet remote, remote database, database organization, prophet dba bolster, Oracle backing and Oracle Consultants.