Java File commands over SSH

我们两清 提交于 2020-01-07 06:17:10

问题


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

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