B4J Code Snippet Access Your MySQL Server Remotely Over SSH

Discussion in 'B4J Code Snippets' started by inakigarm, May 19, 2015.

  1. inakigarm

    inakigarm Well-Known Member Licensed User

    Usually we have a Web Server with MYSQL with a provider, but access to the MYSQL DBs is only opened to local ports (eth1) by default for security reasons. If you want to access your database from a client over Internet (from MySQL Query Browser or other tools), normally you’d have to open up access from your local IP address… but that’s not nearly as secure.

    So instead, we use port-forwarding through an SSH tunnel, so your MySQL client thinks they're connecting to your localhost machine, but it’s really connecting to the other server through the SSH tunnel (the client connects over Internet to the Public IP address assigned to server/domain)

    If you are using the command line ssh in Linux, the command would look like this.
    ssh login@server -L 3306: (where 3306 is MYSQL service IP Port - we connect the ssh tunnel between our computer to the MYSQL server and forwarding all the source traffic with 3306 port destination with a localhost IP and a remote port 3306)


    We can establish this connection in Windows with tools like plink.exe or Putty, but If you want to integrate with your B4J program, you'll have to open with Jshell library.

    You can use the JSch library ( http://www.jcraft.com/jsch/) found also on B4X forum, to establish the tunnel and configure Port Forwarding using the library methods with
    JavaObject (thanks @rwblinn )

    #AdditionalJar: jsch-0.1.51.jar

    Dim user As String = "user"
    Dim host As String = "host"
    Dim port As Int = 22
    Dim pw As String = "pass"
    Dim joSch As JavaObject
    'Java: JSch js = new JSch();
    'Java: Session s = js.getSession("user", "myremotemachine.mycompany.com", 22);
        Dim joS As JavaObject
        joS = joSch.RunMethod(
    "getSession"Array(user, host, port))
    'Java: s.setPassword("mypassword");
    'Java: Properties config = new Properties();
        Dim joP As JavaObject
        joP = joP.InitializeNewInstance(
    'Java: config.put("StrictHostKeyChecking", "no");
    'Java: s.setConfig(config);
    'Java: s.connect();
    Log("Connected to Host...")
        Log("PortFWD to MYSQL...")

    After this tunnel is established and port forwarding is configured, you can Query the MYSQL DataBase with standards Querys from the jSQL B4J library and DBUtils