通过Java中的SSH隧道运行远程命令 [英] Run remote commands through SSH tunnel in Java

查看:104
本文介绍了通过Java中的SSH隧道运行远程命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用SSH连接从远程计算机运行一些命令,但问题如下:

I need to run some commands from a remote computer using an SSH connection, but the problem is the following:

客户端计算机(运行Windows)已连接到我可以看到服务器远程的网络(第二台* nix计算机,在同一网络中)。我可以用它进行SSH连接,但是包含文件的计算机(运行* nix)不在这个网络中,我只能通过在第二台计算机上打开的动态SSH隧道连接到这里,我通常使用PuTTY来配置此连接。然后我就可以访问远程文件。

The client computer (running Windows) is connected to a network where I can see a server remote (second *nix computer, in the same network). I can do SSH connections with it, however the computer that contains the files (running *nix) isn't in this network, I only can connect with this trough a dynamic SSH tunnel open in the second computer, where I normally use PuTTY to configure this connection. Then I've got access to the remote files.

下图代表了体系结构(防火墙就像第二台机器):

The following picture represents the architecture (the firewall is like the second machine):

I需要自动完成这项工作所以我已经用Java和JSch库做了一些测试,这里有一些代码:

I need to make this work automatically so I've done some test with Java and the JSch library, here is some code:

/* Direccion y puerto del host local */
String host = "localhost";
int lport = 5040;


/* Direccion y puerto del host remoto*/
String rhost = "localhost";
int rport = 80;

/* Usuario y password para conectarse al servidor ssh*/
String user = "test";
String pwd = "test";

JSch jsch=new JSch();

Session session=jsch.getSession(user, host, 22);
session.setPassword("test");

Properties config = new Properties();
config.put("StrictHostKeyChecking","no");
session.setConfig(config);
session.connect();

int assinged_port=session.setPortForwardingL(lport, rhost, rport);
System.out.println("localhost:"+assinged_port+" -> "+rhost+":"+rport);

我有连接,但是当我使用object session 运行命令时code>,答案来自第二台机器,而不是我预期的第三台机器。我想知道是否有另一个库有助于使这项工作或我使用错误的JSch。

I got connection, however when I run a command using object session, the answer is from the second machine not from the third machine as I expected. I would like to know if there is another library that helps to make this work or I'm using wrong JSch.

推荐答案

当然,如果你设置 rhost =localhost,连接将到达SSH服务器,而不是资源服务器。
输入正确的主机名,这应该没问题。 (我这样做了一次。)

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.)

如果你想从JSch做两个连接,而不是做本地端口转发,然后连接到这个转发端口,你可以使用我的 ProxySSH 类,找到在JSch wiki中。 (我也是这样做的,就像你在那里一样。)

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.)

这篇关于通过Java中的SSH隧道运行远程命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆