Execute commands on the remote server using Jsch in java

Earlier, we discussed how to connect with a remote server using Java, and this post will cover the points on how to execute commands on that remote server.

We may have to execute single or multiple commands depending on the situation.

We must remember that we don’t make an ssh connection again for each command while trying to execute multiple commands. Because making a connection takes a load on the CPU. We will execute the multiple commands at once on a single ssh connection only.

We will use the JSch library to connect with the remote server. Below is the maven dependency you will have to add to your pom.xml file.

<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>

We will execute –

Let’s see how to execute commands now.

Executing a single command using Jsch

  • First, we must make a connection ( Refer to this post to see how to make a connection ).
  • Execute the command and then capture the command’s output in a variable.

Please note that we will use a key to connect with our remote server, but if you want to connect using a password, we recommend you go through our previous post first. The below program will execute a given command on the server to which it is connected and will return the output of that command.

package codekru;

import java.io.File;
import java.io.InputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class Codekru {

	public Session session;

	public static void main(String[] args) {
		String command = "cd /Users/codekru/jsch-tutorial/"; // command to execute on the server
		Codekru codekru = new Codekru();
		codekru.connect(); // making a connection to the server
		String result = codekru.executeCommand(command); // executing the command
		System.out.println(result);
	}

	public void connect() {
		try {

			JSch jsch = new JSch();
			String user = "codekru"; // your username
			String host = "127.0.0.1"; // your secure server address
			int port = 2222; // your secure server port
			String key = System.getProperty("user.dir") + File.separator + "key.dms";

			jsch.addIdentity(key);
			session = jsch.getSession(user, host, port);
			session.setConfig("StrictHostKeyChecking", "no");
			session.setTimeout(15000);
			session.connect();
			System.out.println("connected");

		} catch (JSchException e) {
			e.printStackTrace();
		}

	}

	private String executeCommand(String command) {
		String finalResult = "";
		try {
			String result = null;

			Channel channel = session.openChannel("exec");
			((ChannelExec) channel).setCommand(command);

			channel.setInputStream(null);// this method should be called before connect()

			((ChannelExec) channel).setErrStream(System.err);
			InputStream inputStream = channel.getInputStream();
			channel.connect();
			byte[] byteObject = new byte[10240];
			while (true) {
				while (inputStream.available() > 0) {
					int readByte = inputStream.read(byteObject, 0, 1024);
					if (readByte < 0)
						break;
					result = new String(byteObject, 0, readByte);
					finalResult = finalResult + result;
				}
				if (channel.isClosed())
					break;

			}
			channel.disconnect();
			System.out.println("Disconnected channel " + channel.getExitStatus());

		} catch (Exception e) {
			e.printStackTrace();
		}
		return finalResult;

	}

}

Let’s move on to execute multiple commands using Jsch.

Executing multiple commands at once on the remote server using Jsch

  • We must add a semicolon(;) between each command we want to run.
  • So, the format will be first_command;second_command;third_command.

Suppose if want to run the below commands –

  • cd /Users/codekru/jsch-tutorial/
  • cd ..
  • pwd

Then, we will write it like “cd /Users/codekru/jsch-tutorial/;cd ..;pwd“.

So, in the above program, we have to write command = “cd /Users/codekru/jsch-tutorial/;cd ..;pwd” and everything else will remain the same.

The program will execute the commands in a single ssh connection only, and the results after executing the final command will be returned by the executeCommand() function. You can run the program and see the magic for yourself.

But, What if we executed an invalid command?

Let’s try to execute an invalid command like “qwerty” and see what happens.

    public static void main(String[] args) {
        String command = "qwerty"; // command to execute on the server
        Codekru codekru = new Codekru();
        codekru.connect(); // making a connection to the server
        String result = codekru.executeCommand(command); // executing the command
        System.out.println(result);
    }

Here we will get the below output –

connected
bash: qwerty: command not found
Disconnected channel 127

The output will be captured as an error stream and outputted to System.err.

We hope that you find this article helpful. If you have any queries or concerns, please write to us in the comments or mail us at admin@codekru.com.

Related Articles –

Liked the article? Share this on

Leave a Comment

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