2010-08-19 169 views
2

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

有没有人找到一种方法让java透明地处理这个隧道?也许一个比自己的jdbc驱动程序包装另一个jdbc驱动器正在Java中处理隧道?

回答

2

我的解决办法是使用Jsch从JCraft 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); 
    } 
} 
相关问题