tags:

views:

31

answers:

2

Currently we have to tunnel over SSH to access our Oracle database. In order to do this we have to make sure than putty or an equivalent program/script is running on the server doing this tunelling before the application is deployed to Tomcat/Glassfish/etc.

Has anybody found a way to have java handle this tunneling transparently? Perhaps a jdbc driver than itself wraps another jdbc drive handling the tunnelling for you right in Java?

+1  A: 

I have used Apache MINA SSHD for a project a while back and I remember that there was support ofr opening tunnels.

You can check out http://mina.apache.org/sshd/ for more info.

Other options are discussed on this quesiton : http://stackoverflow.com/questions/995944/ssh-library-for-java

Peter Tillemans
A: 

My solution was to use Jsch from JCraft http://www.jcraft.com/jsch/ to open a tunnel when my application server starts up. I close the tunnel when the application server shuts down. I do this via a servlet context listener.

int findUnusedPort() {
        final int startingPort = 1025;
        final int endingPort = 1200;
        for (int port = 1025; port < 1200; port++) {
            ServerSocket serverSocket = null;
            try {
                serverSocket = new ServerSocket(port);
                return port;
            } catch (IOException e) {
                System.out.println("Port " + port + "is currently in use, retrying port " + port + 1);
            } finally {
                // Clean up
                if (serverSocket != null) try {
                    serverSocket.close();
                } catch (IOException e) {
                    throw new RuntimeException("Unable to close socket on port" + port, e);
                }
            }
        }
        throw new RuntimeException("Unable to find open port between " + startingPort + " and " + endingPort);
    }

private Session doSshTunnel(int tunnelPort) {
    // SSH Tunnel
    try {
        final JSch jsch = new JSch();
        sshSession = jsch.getSession("username", "sshhost", 22);
        final Hashtable<String, String> config = new Hashtable<String, String>();
        config.put("StrictHostKeyChecking", "no");
        sshSession.setConfig(config);
        sshSession.setPassword("password");

        sshSession.connect();

        int assigned_port = sshSession.setPortForwardingL(tunnelPort, remoteHost, remotePort);

        return sshSession;
    } catch (Exception e) {
        throw new RuntimeException("Unable to open SSH tunnel", e);
    }
} 
Benju