Search code examples
javasshfile-listing

Remote host file operations over SSH2 in java


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?


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.