12

I am trying to list all the files/directory from a remote server using JSch.

But my problem is JSch list all the files with file creation date, time stamp, type of read/write permission etc..,

But in my case I need only the file/directory name in the remote server and no additional information is required..

Below is my piece of Java code..

import java.util.Vector;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class Listremoteserver {
    
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        String SFTPHOST = "xxxxx";
        int    SFTPPORT = 22;
        String SFTPUSER = "xxx";
        String SFTPPASS = "xxxxx";
        String SFTPWORKINGDIR = "/root";
                
        Session     session     = null;
        Channel     channel     = null;
        ChannelSftp channelSftp = null;
        
        try{
            JSch jsch = new JSch();
            session = jsch.getSession(SFTPUSER,SFTPHOST,SFTPPORT);
            session.setPassword(SFTPPASS);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
            channel = session.openChannel("sftp");
            channel.connect();
            channelSftp = (ChannelSftp)channel;
            channelSftp.cd(SFTPWORKINGDIR);
            Vector filelist = channelSftp.ls(SFTPWORKINGDIR);
            for(int i=0; i<filelist.size();i++){
                System.out.println(filelist.get(i).toString());
            }
            
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
}

Results of the above program is

-rw-r--r--    1 root     root         3161 Feb 11  2014 install.log.syslog
-rw-r--r--    1 root     root           18 May 20  2009 .bash_logout
-rw-r--r--    1 root     root          176 Sep 23  2004 .bashrc
-rw-r--r--    1 root     root          176 May 20  2009 .bash_profile
-rw-r--r--    1 root     root          129 Dec  3  2004 .tcshrc
-rw-------    1 root     root         1114 Feb 11  2014 anaconda-ks.cfg
dr-xr-x---    2 root     root         4096 Feb 11  2014 .
-rw-r--r--    1 root     root         9169 Feb 11  2014 install.log
-rw-------    1 root     root         1055 Feb 11  2014 .bash_history
-rw-r--r--    1 root     root          100 Sep 23  2004 .cshrc
dr-xr-xr-x   24 root     root         4096 Feb 12 04:19 ..

4 Answers 4

35

Try running this code. Here we are typecasting the list elements to LsEntry and then printing the required attribute.

import java.io.File;
import java.util.Vector;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;


public class Listremoteserver {


    /**
     * @param args
     */
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        String SFTPHOST = "xxxxx";
        int    SFTPPORT = 22;
        String SFTPUSER = "xxx";
        String SFTPPASS = "xxxxx";
        String SFTPWORKINGDIR = "/tmp";
        String SFTPPRIVATEKEY = "/path/to/xxxxxxxxx.pem";

        Session     session     = null;
        Channel     channel     = null;
        ChannelSftp channelSftp = null;

        try{
            JSch jsch = new JSch();
            File privateKey = new File(SFTPPRIVATEKEY);
            if(privateKey.exists() && privateKey.isFile())
                jsch.addIdentity(SFTPPRIVATEKEY);
            session = jsch.getSession(SFTPUSER,SFTPHOST,SFTPPORT);
            session.setPassword(SFTPPASS);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
            channel = session.openChannel("sftp");
            channel.connect();
            channelSftp = (ChannelSftp)channel;
            channelSftp.cd(SFTPWORKINGDIR);
            Vector filelist = channelSftp.ls(SFTPWORKINGDIR);
            for(int i=0; i<filelist.size();i++){
                LsEntry entry = (LsEntry) filelist.get(i);
                System.out.println(entry.getFilename());
            }
        }catch(Exception ex){
            ex.printStackTrace();
        } finally {
            if(session != null) session.disconnect();
            if(channel != null) channel.disconnect();
        }
    }
}
3
  • 1
    Maybe List<String> fileList instead of Vector
    – Michu93
    Oct 23, 2019 at 16:20
  • Should it not be " Vector filelist = channelSftp.ls(*);" Since you have already navigated to SFTPWORKINGDIR with "channelSftp.cd(SFTPWORKINGDIR);"
    – Achi
    Mar 13, 2020 at 8:33
  • yes it should be Vector filelist = channelSftp.ls(" * "); Aug 31, 2021 at 10:29
5

Use LSEntrySelector for accessing the properties of returned file list.

import java.util.Vector;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.ChannelSftp.LsEntrySelector;
import com.jcraft.jsch.ChannelSftp.LsEntry;


public class Listremoteserver {


    /**
     * @param args
     */
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        String SFTPHOST = "xxxxx";
        int    SFTPPORT = 22;
        String SFTPUSER = "xxx";
        String SFTPPASS = "xxxxx";
        String SFTPWORKINGDIR = "/root";

        Session     session     = null;
        Channel     channel     = null;
        ChannelSftp channelSftp = null;

        try{
            JSch jsch = new JSch();
            session = jsch.getSession(SFTPUSER,SFTPHOST,SFTPPORT);
            session.setPassword(SFTPPASS);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
            channel = session.openChannel("sftp");
            channel.connect();
            channelSftp = (ChannelSftp)channel;
            channelSftp.cd(SFTPWORKINGDIR);
            Vector<String> filelist=new Vector<String>();

            LsEntrySelector selector = new LsEntrySelector() {
                public int select(LsEntry entry)  {
                    final String filename = entry.getFilename();
                    if (filename.equals(".") || filename.equals("..")) {
                        return CONTINUE;
                    }
                    if (entry.getAttrs().isLink()) {
                        filelist.addElement(filename);
                    }
                    else if (entry.getAttrs().isDir()) {
                        //if (keepDirectory(filename)) {
                        filelist.addElement(entry.getFilename());
                        //}
                    }
                    else {
                        //if (keepFile(filename)) {
                        filelist.addElement(entry.getFilename());
                        //}
                    }
                    return CONTINUE;
                }
            };
            channelSftp.ls(SFTPWORKINGDIR,selector);
            for(int i=0; i<filelist.size();i++){
                System.out.println(filelist.get(i).toString());
            }

        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
}
0
3

for sftp you can getlist of file with

Vector<ChannelSftp.LsEntry> list = channelSftp.ls("*.*");
for(ChannelSftp.LsEntry entry:list) {
    System.out.println(entry.getFilename());
}

and there isn't built in function to get list file for exec and shell protocol, you have parse it from InputStream data.

-1

try to exec ls command :

Channel channel=session.openChannel("exec"); 
((ChannelExec)channel).setCommand("cd " + SFTPWORKINGDIR + " && ls");
channel.connect();
channel.run();

Vector filelist = channel.run();
for (int i = 0; i < filelist.size(); i++) {
    System.out.println(filelist.get(i).toString());
}
3
  • line 5 returns an error saying channel.run() returns void. Apr 3, 2017 at 6:20
  • yes its gives error at line 5. @CodelsLife can you update the answer May 25, 2017 at 9:08
  • This answer won't work. channelExec.run() doesn't return a value. And it certainly isn't going to return the ls output all neatly packaged into a list of files for you.
    – Kenster
    May 25, 2017 at 13:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.