【发布时间】:2014-07-07 17:05:34
【问题描述】:
我要做的是设置一个 SOCKS 服务器,然后将其端口添加为 SSH 隧道连接中的本地侦听端口。我想要实现的是动态端口转发(ssh 中的 -D 选项,如果我没记错的话)。我正在使用 JSch 进行 SSH 隧道。这是我到目前为止的代码(复制自http://kahimyang.info/kauswagan/code-blogs/1337/ssh-tunneling-with-java-a-database-connection-example):
int assigned_port;
int local_port=<local listening port goes here>;
// Remote host and port
int remote_port=<remote port goes here>;
String remote_host = "<SSH host goes here>";
String login = "<SSH login goes here>";
String password = "<SSH password goes here>";
try {
JSch jsch = new JSch();
// Create SSH session. Port 22 is your SSH port which
// is open in your firewall setup.
Session session = jsch.getSession(login, remote_host, 22);
session.setPassword(password);
// Additional SSH options. See your ssh_config manual for
// more options. Set options according to your requirements.
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
config.put("Compression", "yes");
config.put("ConnectionAttempts","2");
session.setConfig(config);
// Connect
session.connect();
// Create the tunnel through port forwarding.
// This is basically instructing jsch session to send
// data received from local_port in the local machine to
// remote_port of the remote_host
// assigned_port is the port assigned by jsch for use,
// it may not always be the same as
// local_port.
assigned_port = session.setPortForwardingL(local_port,
remote_host, remote_port);
} catch (JSchException e) {
System.out.println("JSch:" + e.getMessage());
return;
}
if (assigned_port == 0) {
System.out.println("Port forwarding failed!");
return;
}
但是,如果我在客户端计算机上启动本地 SOCKS 代理,JSch 无法将其端口用作本地侦听端口,表示无法绑定。我猜这是因为端口被 SOCKS 服务器占用(这很明显,呵呵)。问题是,使用 JSch 进行动态端口转发的正确方法是什么?
【问题讨论】:
-
你有没有找到用 Java 实现这一目标的方法?
标签: java jsch portforwarding socks ssh-tunnel