2

我现在有一个简单的任务:连接到远程服务器并获取文件列表及其信息(特别是创建日期)。

试过JSch,但感觉就像20年前写的unix app。想切换到 sshj,所以如果可能的话,请提供一些关于如何至少实现文件列表及其信息的代码(理想情况下,我想获得一个 File 对象数组)。

那么我怎样才能实现目标呢?

提前致谢。

注意:AFAIU 只能通过在服务器端安装ls并解析它,不是吗?

4

3 回答 3

3

They have examples bundled with their source distribution. Did you look a them? I found this in 2 minutes: sshj: how to execute remote command example

Edit:

Ok, you could execute for instance (basing on the example I linked):

final Command cmd = session.exec("ls -l /some/interesting/dir");
String lsOutput = cmd.getOutputAsString();

// parse lsOutput and extract required information
...

There is no simplier way if you want to do it over ssh, because it has no notion of files etc. It is just a remote shell. Maybe sftp could provide some better interface here, but I am no expert with sftp.

于 2011-03-30T10:10:40.447 回答
3

这是 sftp (JSCH) 的代码

ChannelSftp sftp = (ChannelSftp)session.openChannel("sftp");
sftp.connect();
sftp.cd(DIRECTORY);
Vector v = null;
v = sftp.ls("*.txt"); //txt files only

与密钥文件一起使用:
JSch jsch = new JSch();
jsch.setKnownHosts(myKonfig.getKnownHostsFile());
String privKeyFile = myKonfig.getPrivateKeyFile();
jsch.addIdentity(privKeyFile);

于 2011-03-30T10:44:27.313 回答
1

哎呀,刚刚看到它没有返回创建时间,只是修改时间。

如果您只是想从远程系统获取文件信息,我建议您使用 sshj 中提供的 SFTPClient 类。

使用:

SFTPClient.ls(directory)

命令查找所有远程文件,然后使用:

SFTPClient.stat(file)

从远程文件中获取所有信息,包括修改日期。

于 2011-03-30T10:39:00.717 回答