SSH Connection Using Java

Posted by MCRSR on April 18, 2023

SSH Connection Using Java

To automate SSH connection using Java, you can use the JSch library. JSch is a pure Java implementation of SSH2, and it provides functionality for secure file transfer, remote execution, and other SSH-related tasks.

Here are the steps to automate SSH connection using Java and JSch:

  • Download the JSch library and add it to your Java project's classpath.
  • Create a new JSch instance:

                                        
    JSch jsch = new JSch();
                                        
                                    
  • Create a new SSH session using the Session class:

                                        
    Session session = jsch.getSession(username, hostname, port);
    session.setPassword(password);
    session.setConfig("StrictHostKeyChecking", "no");
    session.connect();
                                        
                                    

    Replace username, hostname, port, and password with the appropriate values for your SSH server.

  • Create a new Channel instance to execute remote commands:

                                        
    Channel channel = session.openChannel("exec");
                                        
                                    
  • Set the command to execute on the remote server:

                                        
    ((ChannelExec)channel).setCommand(command);
                                        
                                    

    Replace command with the command you want to execute on the remote server.

  • Connect the channel and start the command execution:

                                        
    channel.connect();
                                        
                                    
  • Read the output from the remote command:

                                        
    InputStream in = channel.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
                                        
                                    
  • Close the channel and SSH session:

                                        
    channel.disconnect();
    session.disconnect();
                                        
                                    

Putting it all together, here's an example Java program that automates an SSH connection:

                            
import com.jcraft.jsch.*;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class SshConnection {

    public static void main(String[] args) throws Exception {
        String username = "user";
        String password = "password";
        String hostname = "example.com";
        int port = 22;
        String command = "ls -l";
        
        JSch jsch = new JSch();
        Session session = jsch.getSession(username, hostname, port);
        session.setPassword(password);
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();
        
        Channel channel = session.openChannel("exec");
        ((ChannelExec)channel).setCommand(command);
        
        channel.connect();
        
        InputStream in = channel.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        
        channel.disconnect();
        session.disconnect();
    }

}
                            
                        

how can we read log files which are availbale un another machine using java?

                            
import com.jcraft.jsch.*;

import java.io.*;

public class ReadRemoteLogFile {
    public static void main(String[] args) {
        String username = "remote-username";
        String password = "remote-password";
        String hostname = "remote-hostname";
        int port = 22;
        String logFilePath = "/path/to/log/file";
        
        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession(username, hostname, port);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();
            
            ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
            sftpChannel.connect();
            
            InputStream inputStream = sftpChannel.get(logFilePath);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }
            
            bufferedReader.close();
            inputStream.close();
            
            sftpChannel.disconnect();
            session.disconnect();
        } catch (JSchException | IOException e) {
            e.printStackTrace();
        }
    }
}
                            
                        

Replace /path/to/log/file with the actual path to the log file on the remote machine.

This code creates an InputStream from the log file on the remote machine and then reads its contents using a BufferedReader. Each line of the log file is printed to the console.

Note that you may need to handle exceptions and errors that can occur during file I/O operations or the SSH connection. Also, be sure to close the input stream and the SFTP channel when you're done reading the log file.