How do I run a simple command over SSH with JSch?

To execute a simple command over SSH using JSch (Java Secure Channel), you can use the ChannelExec channel provided by the JSch library. Here’s how you can achieve that:

Maven Dependency:

If you’re using Maven, include the JSch library in your pom.xml file:

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version> <!-- Use the latest version -->
</dependency>

Code Example

The following Java snippet demonstrates how to use JSch to connect to a remote server via SSH and execute a command:

package org.kodejava.jsch;

import com.jcraft.jsch.*;

import java.io.InputStream;

public class SSHCommandExecutor {
   public static void main(String[] args) {
      String host = "example.com";
      String user = "username";
      String password = "password";
      String command = "ls -l"; // Example command

      JSch jsch = new JSch();
      Session session = null;

      try {
         // Create a session with the remote host
         session = jsch.getSession(user, host, 22); // Port 22 is the default SSH port
         session.setPassword(password);

         // Configure to avoid asking for key confirmation
         java.util.Properties config = new java.util.Properties();
         config.put("StrictHostKeyChecking", "no");
         session.setConfig(config);

         // Connect to the remote host
         session.connect();

         // Open an exec channel for the command
         Channel channel = session.openChannel("exec");
         ((ChannelExec) channel).setCommand(command);

         // Get the input stream to read command output
         InputStream inputStream = channel.getInputStream();

         // Connect the channel
         channel.connect();

         // Read and print the command output
         byte[] buffer = new byte[1024];
         int bytesRead;
         while ((bytesRead = inputStream.read(buffer)) != -1) {
            System.out.print(new String(buffer, 0, bytesRead));
         }

         // Disconnect the channel and session
         channel.disconnect();
         session.disconnect();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

Explanation:

  1. Setup and Configuration:
    • The JSch object initializes the library.
    • Use jsch.getSession(user, host, port) to establish an SSH session with the remote host.
    • Set the session password and configure session properties (e.g., disable strict host key checking).
  2. Opening a Channel:
    • Use the session.openChannel("exec") to execute a command on the server.
    • Set the desired command to ((ChannelExec) channel).setCommand(command).
  3. Reading Output:
    • Once the channel is connected, the command’s output is available via the InputStream provided by channel.getInputStream().
  4. Cleanup:
    • Always disconnect the channel and session to free up resources.

Notes:

  • StrictHostKeyChecking: It’s generally good to enable strict host key checking for security. Change the "no" to "yes" or configure known hosts separately.
  • Error Handling: Add proper error handling to handle any SSH-specific exceptions.
  • Security: Avoid hardcoding sensitive information like passwords. Instead, consider using environment variables or a secure vault.

With this setup, you can securely execute commands over SSH using JSch.

Leave a Reply

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