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

2024-03-15

目前我们必须通过 SSH 隧道来访问我们的 Oracle 数据库。为了做到这一点,我们必须确保在将应用程序部署到 Tomcat/Glassfish/等之前,在服务器上运行 putty 或等效的程序/脚本来进行此调整。

有没有人找到一种方法让java透明地处理这个隧道?也许一个 jdbc 驱动程序本身包装了另一个 jdbc 驱动程序,在 Java 中为您处理隧道?


我的解决方案是使用 JCraft 的 Jschhttp://www.jcraft.com/jsch/ http://www.jcraft.com/jsch/当我的应用程序服务器启动时打开隧道。当应用程序服务器关闭时我关闭隧道。我通过 servlet 上下文侦听器执行此操作。

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);
    }
} 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过 SSH 隧道连接到 jdbc 中的 Oracle 数据库 的相关文章

随机推荐