我要做的是设置一个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进行动态端口转发的正确方法是什么?
发布于 2014-05-25 16:32:06
以下是对-D的描述
指定本地“动态”应用程序级端口转发。这是通过分配一个套接字来侦听本地端的端口(可以选择绑定到指定的bind_address )来实现的。无论何时连接到该端口,连接都通过安全通道转发,然后应用协议用于确定从远程计算机连接到何处。目前支持SOCKS4和SOCKS5协议,ssh将充当SOCKS服务器。只有根用户才能转发特权端口。还可以在configura- tion文件中指定动态端口转发。
@Kenster关于ssh所做的事情是正确的,但我认为您想要的不是远程运行SOCKS代理,而是用jsch实现Java代理服务器(然后将它贡献给jsch)。
发布于 2014-05-23 18:31:57
如果SOCKS代理在远程服务器上运行,则可以从本地服务器上的端口到远程服务器上的SOCKS代理端口创建SSH隧道。一旦您设置了它,您的SOCKS能力的客户端就可以像SOCKS代理一样使用本地隧道端口。
OpenSSH ssh程序和windows Putty实用程序具有内置SOCKS代理功能。你可以用其中之一。
https://stackoverflow.com/questions/23742809
复制相似问题