2010-08-19 258 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); 
    } 
} 
相關問題