希望将内网的windows的远程桌面,通过公网服务器透出来,然后随时随地就可以操作自己的电脑。于是在网上找到了一种隧道的实现方式,通过Putty工具建立隧道,但每次打开都需要重新输入参数,操作非常繁琐,就想用java写个GUI小工具实现。核心代码如下图:
添加maven依赖
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
工具代码:
package com.yx.ssh.core.channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public class SSHChannel {
String host;//服务器ip
int port;//服务器ssh端口
String username;//服务器登录用户
String password;//服务器登录密码
int remotePort;//服务器远程转发的端口
int localPort;//本地接收端口
JSch jSch;//工具类
Session session;//会话
public SSHChannel(String host, int port, String username, String password, int remotePort, int localPort) {
this.host = host;
this.port = port;
this.username = username;
this.password = password;
this.remotePort = remotePort;
this.localPort = localPort;
this.jSch = new JSch();
}
public void create() throws JSchException {
session = jSch.getSession(username, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
session.setPortForwardingR(remotePort, "localhost", localPort);
System.out.printf("ssh隧道配置成功:localhost:%s -> %s:%s \n", localPort, host, remotePort);
}
public void close() throws JSchException {
if(session==null){
System.out.println("ssh隧道未创建");
return;
}
if(!session.isConnected()){
System.out.println("ssh隧道配置已经关闭");
return;
}
session.delPortForwardingR(remotePort);
session.disconnect();
System.out.printf("ssh隧道配置关闭:localhost:%s -X-> %s:%s \n", localPort, host, remotePort);
}
public boolean isConnect(){return session.isConnected();}
}
使用方法
JSONObject json= JSON.parseObject("");
//隧道参数配置
SSHChannel channel=new SSHChannel(json.getString("host"),
json.getInteger("port"),
json.getString("username"),
json.getString("password"),
json.getInteger("remotePort"),
json.getInteger("localPort"));
//隧道创建
channel.create();
//隧道关闭
channel.close();
//隧道连接状态
boolean status=channel.isConnect();