问题
I'm creating a java program which does a lot over ssh.
In my program, I need to be able to run methods such as "listFiles()" on a remote host. I also need to be able to run a couple commands from Apache Commons io (I'm using the "FileUtils" class). I've seen programs such as JSch, but none of them have enough flexibility when it comes to file manipulation and transfer.
Could anyone suggest an alternate program or approach to my problem?
回答1:
On the contrary, JSch does support file transfer: http://www.jcraft.com/jsch/examples/ScpTo.java.html
As for listing files on the remote host, you can't just run a java command there using Apache Commons FileUtils. What you'd have to do is remotely execute a command on the remote OS - the equivalent of doing this via command-line ssh:
ssh remotehost ls /path/to/remote/dir
This is pretty much true of any ssh library you choose, not just JSch.
So, in terms of JSch, this would be (assuming you've already set up and connected a Jsch ssh session):
ChannelExec channel= (ChannelExec) session.openChannel("exec");
channel.setCommand("ls /path/to/remote/dir");
InputStream in=channel.getInputStream();
channel.connect()
// read your ls-output from the input stream here
channel.disconnect()
来源:https://stackoverflow.com/questions/19930795/java-file-commands-over-ssh