JSch 實現 SSH 端口轉發

 1 package com.yinger.webservice.test;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.ResultSet;
 6 import java.sql.Statement;
 7 
 8 import com.jcraft.jsch.JSch;
 9 import com.jcraft.jsch.JSchException;
10 import com.jcraft.jsch.Session;
11 
12 public class SSHexample {
13 
14     static int localPort = 3306;// 本地端口
15     static String remoteHost = "localhost";// 遠程MySQL服務器
16     static int remotePort = 3306;// 遠程MySQL服務端口
17 
18     public static void startSSH() throws JSchException {
19         // SSH鏈接用戶名
20         String sshUser = "root";
21         // SSH鏈接密碼
22         String sshPassword = "Shopex000000";
23         // SSH服務器
24         String sshHost = "120.76.101.77";
25         // SSH訪問端口
26         int sshPort = 22;
27         JSch jsch = new JSch();
28         Session session = jsch.getSession(sshUser, sshHost, sshPort);
29         session.setPassword(sshPassword);
30         // 設置第一次登錄的時候提示,可選值:(ask | yes | no)
31         session.setConfig("StrictHostKeyChecking", "no");
32         session.connect();
33         // 打印SSH服務器版本信息
34         System.out.println(session.getServerVersion());
35         // 設置SSH本地端口轉發,本地轉發到遠程
36         int assinged_port = session.setPortForwardingL(localPort, remoteHost, remotePort);
37         // 刪除本地端口的轉發
38         // session.delPortForwardingL(localPort);
39         // 斷開SSH連接
40         // session.disconnect();
41         // 設置SSH遠程端口轉發,遠程轉發到本地
42         // session.setPortForwardingR(remotePort, remoteHost, localPort);
43         System.out.println("localhost:" + assinged_port + " -> " + remoteHost + ":" + remotePort);
44     }
45 
46     public static void testSSH() throws Exception {
47         Connection conn = null;
48         Statement st = null;
49         ResultSet rs = null;
50         try {
51             Class.forName("com.mysql.jdbc.Driver");
52             // 設置SSH本地端口轉發後,訪問本地ip+port就能夠訪問到遠程的ip+port
53             conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
54             st = conn.createStatement();
55             String sql = "select * from test limit 10";
56             rs = st.executeQuery(sql);
57             while (rs.next())
58                 System.out.println(rs.getString(1));
59         } catch (Exception e) {
60             throw e;
61         } finally {
62             if (rs!=null) {rs.close();rs=null;}
63             if (st!=null) {st.close();st=null;}
64             if (conn!=null) {conn.close();conn=null;}
65         }
66     }
67 
68     public static void main(String[] args) throws Exception {
69         startSSH();
70         testSSH();
71     }
72 }
相關文章
相關標籤/搜索