Run remote commands through SSH tunnel in Java

余生颓废 提交于 2019-12-04 18:55:55

Of course, if you set rhost = "localhost", the connection will arrive at the SSH server, and not at the "Resource" server. Put the right host name in, and it should be no problem. (I did this once.)

If you want to do both connections from JSch, instead of doing a local port forwarding and then connecting to this forwarded port, you can use my ProxySSH class, to find in the JSch wiki. (I did this, too, in a similar situation like you have there.)

curio1729

You have to create session on the second server after port forwarding. Then connection is established to the server behind firewall.

Look at this code for example.What this code does is create a local port forwarding to the ssh port on the target system, then connects through it. The running of the hostname command illustrates that it is, indeed, running on the forwarded-to system.

You have to open another session that makes use of the forwarded port.

Session sessionA = jsch.getSession("usernameA", "hostA");
// ...
sessionA.connect();

int forwardedPort = 2222; // any port number which is not in use on the local machine
sessionA.setPortForwardingL(forwardedPort, "hostB", 22);

Session sessionB = jsch.getSession("usernameB", "localhost", forwardedPort);
// ...
sessionB.connect();

// Use sessionB here to execute your command
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!