Execute shell script on the remote server from Java project using JSch Library

Execute shell script on the remote server from Java project using JSch Library

For reducing programming efforts, shell scripting can be very handy. Shell scripting is combined with series of shell commands. In one of our automation project, we needed to run shell script from our Java program. In this article, I am going to demonstrate how we can execute shell script from Java program.

We need JSch java library here.

We can directly download the jar or can add it in the gradle or maven dependencies. In build.gradle file we can include followings inside the dependencies if we are using Gradle as build tool.

dependencies {
    compile 'com.jcraft:jsch:0.1.54'
}

Or, we can add followings into our pom.xml file if we are using Maven as build tools inside the dependencies:

<dependency>
  <groupId>jsch</groupId>
  <artifactId>jsch</artifactId>
  <version>0.1.29</version>
</dependency>

After adding our dependencies let's find out how we can connect with remote server over SSH protocol.

To connect with remote server, we need following server information:

  1. Remote host IP
  2. Remote host port
  3. Host user name
  4. Host password

Now let's first import all the necessary libraries

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

Here the InputStream is used to read data from a source and the InputStreamReader class works with other input streams which is also known as a bridge between byte streams and character streams. BufferReader reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

Now let's create our class for executing shell script

public class RemoteShellExecutor{

}

Then let's create the static variables for host-ip, port, user-name and password

    private static String userName = "userName "; // username for remote host
    private static String passWord = "passWord "; // password of the remote host
    private static String host = "xxx.xxx.xxx.xxx"; // remote host address
    private static int port = 1234;

Now let's create our main method which will execute remote shell file, it takes file name as arguments which needs to be executed.

public int executeShellFile(String scriptFileName) {

}

We need to create a new JSch object first which will execute our shell script file.

JSch jsch = new JSch();

Then let's create session for JSch

Session session = jsch.getSession(userName, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(passWord);
session.connect();

This will open a new session with our provided remote server. Once connection is established we can initiate execution channel over the session.

ChannelExec channelExec = (ChannelExec) session.openChannel("exec");

Now we want to read all the date from remote side

InputStream in = channelExec.getInputStream();

Common format for executing shell script is

sh scriptFile.sh

Let's set the command for the script and execute it

channelExec.setCommand("sh " + scriptFileName);
channelExec.connect();

Now let's read the result from input stream, put them into our buffer reader and print them line by line

BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
      System.out.println("Clearing -> " + line);
 }

At this point we need to know the exit status of remote command and disconnect the channel and session.

int exitStatus = channelExec.getExitStatus();
channelExec.disconnect();
session.disconnect();

Full project can be found at https://github.com/humayun-ashik/execute-remote-shellscript

Thank you for reading :)