Java code to run a remote script on remote host using SSH

SSH

SSH (Secure Shell) provides support for secure remote login, secure file transfer, and secure TCP/IP and X11 forwarding. SSH uses a client-server model for –
1. Establishing a secured connection between two parties,
2. Authenticating the two parties, and
3. Encrypting the data transmissions between the two parties.

To make the information transmission secure, SSH uses different cryptographic techniques like symmetrical encryption, asymmetrical encryption, and hashing.

JSch

JSch is a Java implementation of SSH2. JSch allows to connect to an sshd server and use port forwarding, X11 forwarding, file transfer, etc.

Jar file required – jsch-0.1.42.jar

Remote Script

We have a remote script ‘myscript.sh‘ on our remote host ‘192.168.1.1‘. The script is present under the home directory of user ‘testuser‘. We will invoke this remote script from our local machine and will print the messages returned by the script.

Contents of ‘myscript.sh‘ :-

#!/bin/bash

echo "hello $1"

Java code

Java code for running the remote script:-

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;    

public class RemoteScriptExec {

    public static void main(String[] args) {

        JSch jsch = new JSch();

        Session session;
        try {

            // Open a Session to remote SSH server and Connect.
            // Set User and IP of the remote host and SSH port.
            session = jsch.getSession("testuser", "192.168.1.1", 22);
            // When we do SSH to a remote host for the 1st time or if key at the remote host 
            // changes, we will be prompted to confirm the authenticity of remote host. 
            // This check feature is controlled by StrictHostKeyChecking ssh parameter. 
            // By default StrictHostKeyChecking  is set to yes as a security measure.
            session.setConfig("StrictHostKeyChecking", "no");
            //Set password
            session.setPassword("testPassword");
            session.connect();

            // create the execution channel over the session
            ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
            // Set the command to execute on the channel and execute the command
            channelExec.setCommand("sh myscript.sh Rajesh");
            channelExec.connect();

            // Get an InputStream from this channel and read messages, generated 
            // by the executing command, from the remote side.
            InputStream in = channelExec.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // Command execution completed here.

            // Retrieve the exit status of the executed command
            int exitStatus = channelExec.getExitStatus();
            if (exitStatus > 0) {
                System.out.println("Remote script exec error! " + exitStatus);
            }
            //Disconnect the Session
            session.disconnect();
        } catch (JSchException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Output

The execution of remote script returns following message:-

hello Rajesh

 

Leave a Reply

Your email address will not be published. Required fields are marked *