且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过SSH隧道连接到jdbc中的Oracle数据库

更新时间:2022-11-30 09:05:05

我的解决方案是使用来自JCraft的Jsch http://www.jcraft.com/jsch/在我的应用程序服务器启动时打开隧道.当应用程序服务器关闭时,我关闭了隧道.我是通过servlet上下文侦听器完成的.

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);
    }
}