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 }

 

posted on 2016-08-25 10:09  guodefu909  阅读(3419)  评论(0编辑  收藏  举报

导航