我想要做的是设置一个 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 无法将其端口用作本地监听端口,表示无法绑定(bind)。我推测这是因为该端口被 SOCKS 服务器占用(这很明显,呵呵)。问题是,使用 JSch 进行动态端口转发的正确方法是什么?
最佳答案
如果 SOCKS 代理在远程服务器上运行,您可以建立从本地服务器上的端口到远程服务器上的 SOCKS 代理端口的 SSH 隧道。设置完成后,支持 SOCKS 的客户端就可以使用本地隧道端口,就像它是 SOCKS 代理一样。
OpenSSH ssh
程序和 Windows Putty
实用程序具有内置的 SOCKS 代理功能。您可以只使用其中之一。
关于Java:SSH隧道-设置本地SOCKS作为监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23742809/