通过SSH的Java文件命令 [英] Java File commands over SSH

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

问题描述

我正在创建一个在ssh上执行很多的Java程序.

I'm creating a java program which does a lot over ssh.

在我的程序中,我需要能够在远程主机上运行诸如"listFiles()"之类的方法.我还需要能够从Apache Commons io运行几个命令(我正在使用"FileUtils"类).我见过诸如JSch之类的程序,但是它们在文件操作和传输方面都没有足够的灵活性.

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?

推荐答案

相反,JSch确实支持文件传输:

On the contrary, JSch does support file transfer: http://www.jcraft.com/jsch/examples/ScpTo.java.html

对于列出远程主机上的文件,您不能仅使用Apache Commons FileUtils在此处运行Java命令.您要做的是在远程OS上远程执行命令-等效于通过命令行ssh来执行此操作:

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

这对您选择的任何ssh库都是正确的,而不仅仅是JSch.

This is pretty much true of any ssh library you choose, not just JSch.

因此,就JSch而言,这将是(假设您已经建立并连接了一个Jsch ssh会话):

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

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

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