我需要使用SSH / SFTP连接从远程计算机获取一些文件,但问题如下:
我将运行我的应用程序的客户端计算机(运行Windows)连接到一个网络,在那里我可以看到服务器远程(第二台计算机,运行Unix,在同一网络中)。我可以用它做SSH连接,但是包含文件的计算机(运行Unix)不在这个网络中,我只能通过在第二台计算机上打开的动态隧道SSH连接,我通常使用PuTTY进行配置这个连接,然后我有权访问远程文件。
下图代表了架构,(防火墙就像第二台机器)
我需要自动完成这项工作所以我已经用Java和JSch库做了一些测试,这里有一些代码:
/* 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);
我得到了连接,但是当我使用对象session
运行命令时,答案来自第二台机器而不是我预期的第三台机器,我想知道,如果有另一个库有助于使这项工作或我'使用错误的JSch。
这与your other question(你使用shell连接而不是文件传输)的答案相同:
将正确的hostName设置为rhost
,即从防火墙服务器看到的目标服务器的名称。
如果它适用于HTTP,我想防火墙服务器也有一个运行的HTTP代理,它将端口80上的请求转发到你的目标端口......当然,如果它也应该是SSH,它就不能为SSH做这个服务器本身。
如果你想从JSch做两个连接,而不是做本地端口转发,然后连接到这个转发端口,你可以使用我的ProxySSH
类来查找in the JSch wiki。
使用local port forwarding(又名SSH tunnel)通过防火墙打开到服务器的SSH / SFTP连接。然后,您可以直接从本地计算机将文件下载到服务器:
Session firewallSession = jsch.getSession("firewall_username", "firewall", 22);
// ...
firewallSession.connect();
int forwardedPort = 2222; // any port number which is not in use on the local machine
firewallSession.setPortForwardingL(forwardedPort, "server", 22);
Session session = jsch.getSession("server_usernam", "localhost", forwardedPort);
// ...
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp channelSftp = (ChannelSftp)channel;
channelSftp.get("/remote/path/on/server/file.txt", "C:\\local\\path\\file.txt");