How do I list directory contents on a remote server using JSch?

To list the contents of a directory on a remote server using JSch (a Java library for SSH), you need to establish an SSH connection and use the SFTP protocol to query the directory. Here’s how you can do it programmatically:

Steps to List Directory Contents:

  1. Establish a session: Connect to the remote server with the appropriate credentials (host, port, username, password/key).
  2. Access the SFTP Channel: Open and connect a ChannelSftp instance.
  3. Change to the Target Directory: Navigate to the directory you want to list.
  4. Retrieve Directory Contents: Use the ls method of ChannelSftp to get the directory listing.

Here’s example code for this:

package org.kodejava.jsch;

import com.jcraft.jsch.*;

import java.util.Vector;

public class SFTPListDirectories {
   public static void main(String[] args) {
      String host = "example.com";
      int port = 22; // Default SSH port
      String user = "username";
      String password = "password"; // Or setup key-based authentication
      String remoteDirectory = "/path/to/remote/directory";

      JSch jsch = new JSch();

      try {
         // Establish SSH session
         Session session = jsch.getSession(user, host, port);
         session.setPassword(password);

         // Avoid asking for key confirmation
         session.setConfig("StrictHostKeyChecking", "no");
         session.connect();

         System.out.println("Connected to the server!");

         // Open SFTP channel
         Channel channel = session.openChannel("sftp");
         channel.connect();
         ChannelSftp channelSftp = (ChannelSftp) channel;

         System.out.println("SFTP Channel opened and connected.");

         // Change to the remote directory
         channelSftp.cd(remoteDirectory);

         // List files in the directory
         Vector<ChannelSftp.LsEntry> fileList = channelSftp.ls(remoteDirectory);

         System.out.println("Files in directory:");
         for (ChannelSftp.LsEntry entry : fileList) {
            System.out.println(entry.getFilename());
         }

         // Disconnect the channel and session
         channelSftp.exit();
         channel.disconnect();
         session.disconnect();
         System.out.println("Disconnected from the server.");
      } catch (JSchException | SftpException e) {
         e.printStackTrace();
      }
   }
}

Explanation of the Code:

  1. Session and Configuration:
    • A Session object is created and authenticated using username/password.
    • Set "StrictHostKeyChecking" to "no" if you want to bypass host key verification for testing purposes (not recommended in production).
  2. ChannelSftp:
    • The ChannelSftp object is used to navigate and interact with files/directories on the remote server.
    • The cd method is used to change to the target directory.
    • The ls method returns a Vector of ChannelSftp.LsEntry objects representing the contents.
  3. Directory Listing:
    • The getFilename() method retrieves the name of the file for each entry in the directory.
    • You can list files, directories, or other details by iterating over the entries.

Key Points to Remember:

  • The ls method may return not just files but also . (current directory) and .. (parent directory). You can filter these out if needed.
  • If using key-based authentication, you can set your private key with JSch.addIdentity("path/to/private/key").
  • Use try-with-resources or ensure proper closing of sessions and channels to avoid resource leaks.

Output Example:

For a remote directory /home/user/data containing the files:

file1.txt
file2.log
subdir

The output will be:

Connected to the server!
SFTP Channel opened and connected.
Files in directory:
.
..
file1.txt
file2.log
subdir
Disconnected from the server.

Maven Dependencies

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>

Maven Central

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.