Question

I've got a simple task for now: connect to a remote server and get list of files and their info (in particular date of creation).

Tried JSch, but it's like writing unix app 20 years ago. Would like to switch to sshj so if it's possible, please provide some code on how to achieve at least file listing and their info (ideally, I would like to get an array of File objects).

So how can I achieve the goal?

Thanks in advance.

NOTE: AFAIU it's only possible by having ls on server side and parsing it, isn't it?

Was it helpful?

Solution

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.

OTHER TIPS

Here is the code for sftp (JSCH)

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

Use with keyfile:
JSch jsch = new JSch();
jsch.setKnownHosts(myKonfig.getKnownHostsFile());
String privKeyFile = myKonfig.getPrivateKeyFile();
jsch.addIdentity(privKeyFile);

Oops, just saw that it doesn't return the creation time, just the modification time.

If you're just looking to get file information from the remote system, I would recommend using the SFTPClient class that's provided within sshj.

use the:

SFTPClient.ls(directory)

command to find all the remote files, then use the:

SFTPClient.stat(file)

to get all the information from the remote files including the date of modification.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top