How to connect to an FTP server from an existing c

2019-04-02 17:12发布

问题:

Currently I am using Reflection for Unix and OpenVMS. I connect to a Unix server. Once connected, I establish a new FTP connection to the target server. Here is how the console window look like:

login: xxx 
Password : xxx 
// Now I'm connected to UNIX
// Next I am connecting to that FTP 
ftpLogin@hostName :/whatever/.../ $ ftp someftp.example.com 
Conencted 
Name: myLogin 
Password: 
XXX 
Login OK 

I tried to replicate the same steps programmatically, but got confused with this "double connection" thing. I was able to connect to Unix only, but then I don't know how to proceed.

JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
    session.setPassword(password);
    session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect(); 

Now that I am connected to Unix, how do I proceed with this step ftpLogin@hostName :/whatever/.../ $ ftp someftp.example.com?

I think I might only need to send a command, something like

sftpChannel.setCommand("ftpLogin@hostName :/whatever/.../ $ ftp someftp.example.com ?") 

How can I connect to a separate FTP from an existing "session/connection"?

回答1:

You typically use the local port forwarding for this.

In JSch, after you connect, call the setPortForwardingL:

int ftpPort = session.setPortForwardingL(0, "someftp.example.com", 21);

And then connect a local FTP client (e.g. the FTPClient from Apache Commons) to the localhost:ftpPort:

FTPClient ftp = new FTPClient();
ftp.connect("localhost", ftpPort);
ftp.login("myLogin", password);