我想 ssh 到代理后面的机器,然后在我的 java 程序中进行端口转发。 (为了能够通过 ssh 连接到盒子,我应该首先通过 ssh 连接到代理计算机)。我通常通过在 ~/.ssh/config 文件中包含以下条目来做到这一点:
ProxyCommand ssh proxyhost.com -t nc %h %p
IdentityFile /home/username/username_dsa_key
然后我运行以下命令进行端口转发,将 hostmachine.com:54321 映射到我的 localhost:12345:
ssh -A -L12345:localhost:54321 hostmachine.com
现在我想使用 Jsch 库执行这些操作,但我不知道在 session 上打开 channel 后如何连接到第二个主机:
String proxyHost = "proxyhost.com";
String host = "hostmachine.com";
int lport = 12345;
String rhost = "localhost";
int rport = 54321;
JSch jsch=new JSch();
jsch.setKnownHosts("/home/{user}/.ssh/known_hosts");
jsch.addIdentity("/home/{user}/.ssh/{user}_dsa_key",passphrase);
Session session1 = jsch.getSession(user,proxyHost,22);
session1.connect(3000);
System.out.println(session1.isConnected());
Channel channel = session1.openChannel("shell");
////// Now what? :)
channel.disconnect();
session1.disconnect();
有什么想法吗?
p.s:我已阅读 www.jcraft.com/jsch/examples/中的示例,但不幸的是,它们在这种情况下没有帮助。
谢谢!
最佳答案
我建议你尝试一下
http://www.jcraft.com/jsch/examples/JumpHosts.java.html
,但如果使用 native “ssh”命令很重要,您会发现该类 jsch-0.1.50的Session.java注释中的ProxyCommand,
/*
// setProxyCommand("ssh -l user2 host2 -o 'ProxyCommand ssh user1@host1 nc host2 22' nc %h %p")
public void setProxyCommand(String command){
setProxy(new ProxyCommand(command));
}
class ProxyCommand implements Proxy {
String command;
Process p = null;
InputStream in = null;
OutputStream out = null;
ProxyCommand(String command){
this.command = command;
}
public void connect(SocketFactory socket_factory, String host, int port, int timeout) throws Exception {
String _command = command.replace("%h", host);
_command = _command.replace("%p", new Integer(port).toString());
p = Runtime.getRuntime().exec(_command);
in = p.getInputStream();
out = p.getOutputStream();
}
public Socket getSocket() { return null; }
public InputStream getInputStream() { return in; }
public OutputStream getOutputStream() { return out; }
public void close() {
try{
if(p!=null){
p.getErrorStream().close();
p.getOutputStream().close();
p.getInputStream().close();
p.destroy();
p=null;
}
}
catch(IOException e){
}
}
}
*/
关于java - 如何使用 jsch 和代理命令进行端口转发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21567031/