JSch is an excellent library for supporting remote connections over ssh, including the execution of remote commands (or shell scripts).

There are numerous examples of how to use JSch at JSch Examples, but pay particular attention to Exec.

At its base, what one does is:

  1. Obtain credentials
  2. Create a Session
  3. Open a Channel within the Session
  4. Deal with streams as desired

While typing, the OP also posted an additional question and an example. The example from http://www.codesandscripts.com/2014/10/java-program-to-execute-shell-scripts-on-remote-server.html seems fine as well.

As to the pushing the script to the server, start by using either scp or sftp (the latter we've found to be more reliable) to move the file to the remote machine, be sure to send an exec of chmod u+x, and then invoke the script.

Answer from KevinO on Stack Overflow
Top answer
1 of 2
6

JSch is an excellent library for supporting remote connections over ssh, including the execution of remote commands (or shell scripts).

There are numerous examples of how to use JSch at JSch Examples, but pay particular attention to Exec.

At its base, what one does is:

  1. Obtain credentials
  2. Create a Session
  3. Open a Channel within the Session
  4. Deal with streams as desired

While typing, the OP also posted an additional question and an example. The example from http://www.codesandscripts.com/2014/10/java-program-to-execute-shell-scripts-on-remote-server.html seems fine as well.

As to the pushing the script to the server, start by using either scp or sftp (the latter we've found to be more reliable) to move the file to the remote machine, be sure to send an exec of chmod u+x, and then invoke the script.

2 of 2
1

Here is a JSch example to SSH login (password) a remote server and runs a shell script.

package com.mkyong.io.howto;

import com.jcraft.jsch.*;

import java.io.IOException;
import java.io.InputStream;

public class RunRemoteScript {

    private static final String REMOTE_HOST = "1.1.1.1";
    private static final String USERNAME = "";
    private static final String PASSWORD = "";
    private static final int REMOTE_PORT = 22;
    private static final int SESSION_TIMEOUT = 10000;
    private static final int CHANNEL_TIMEOUT = 5000;

    public static void main(String[] args) {

        String remoteShellScript = "/root/hello.sh";

        Session jschSession = null;

        try {

            JSch jsch = new JSch();
            jsch.setKnownHosts("/home/mkyong/.ssh/known_hosts");
            jschSession = jsch.getSession(USERNAME, REMOTE_HOST, REMOTE_PORT);

            // not recommend, uses jsch.setKnownHosts
            //jschSession.setConfig("StrictHostKeyChecking", "no");

            // authenticate using password
            jschSession.setPassword(PASSWORD);

            // 10 seconds timeout session
            jschSession.connect(SESSION_TIMEOUT);

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

            // run a shell script
            channelExec.setCommand("sh " + remoteShellScript + " mkyong");

            // display errors to System.err
            channelExec.setErrStream(System.err);

            InputStream in = channelExec.getInputStream();

            // 5 seconds timeout channel
            channelExec.connect(CHANNEL_TIMEOUT);

            // read the result from remote server
            byte[] tmp = new byte[1024];
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0) break;
                    System.out.print(new String(tmp, 0, i));
                }
                if (channelExec.isClosed()) {
                    if (in.available() > 0) continue;
                    System.out.println("exit-status: "
                         + channelExec.getExitStatus());
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (Exception ee) {
                }
            }

            channelExec.disconnect();

        } catch (JSchException | IOException e) {

            e.printStackTrace();

        } finally {
            if (jschSession != null) {
                jschSession.disconnect();
            }
        }

    }
}

Refer to this example How to run a remote shell script in Java

🌐
Mkyong
mkyong.com › home › java › java – run shell script on a remote server
Java - Run shell script on a remote server - Mkyong.com
October 1, 2020 - This article shows how to use JSch library to run or execute a shell script in a remote server via SSH. pom.xml · <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency> This Java example uses JSch to SSH login a remote server (using password), and runs a shell script hello.sh.
Discussions

Executing Shell Scripts from Java Program by ssh to remote server - Stack Overflow
Below is the program that I am using to ssh to one of the remote servers and its working fine. My question is- Is there any way I can execute the shell scripts that I have on my windows machine o... More on stackoverflow.com
🌐 stackoverflow.com
Execute the shell script present in remote server using java - Stack Overflow
You might want to echo out the current directory (found by executing pwd in your script) to make sure you're really running where you think you are. ... Thanks ..Changed the directory..! ... The December 2024 Community Asks Sprint has been moved to March 2025 (and... Stack Overflow Jobs is expanding to more countries · 1 how to excute shell script on difference machine using java · 0 How to run java -jar command from Shell script from remote ... More on stackoverflow.com
🌐 stackoverflow.com
April 26, 2017
bash - Any possibility to execute shell script from java file? - Unix & Linux Stack Exchange
I have one Java file named app.java which extracts the servers in my application. I need to connect to every server in that list and extract the logs. In loop, I have to call script for connecting to More on unix.stackexchange.com
🌐 unix.stackexchange.com
How to call Linux shell scripts from java remotely - Programming & Development - Spiceworks Community
"I have a shell script in remote linux machine (dir: ctl_files/kfg). I want to call this from local machine (windows). How I can do that? I have written below code: package com.test; import java.io.IOException; public cl… More on community.spiceworks.com
🌐 community.spiceworks.com
0
December 29, 2009
🌐
Humayun Ahmed Ashik
humayun-ashik.hashnode.dev › 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
July 10, 2021 - We need to create a new JSch object first which will execute our shell script file. ... Session session = jsch.getSession(userName, host, port); session.setConfig("StrictHostKeyChecking", "no"); session.setPassword(passWord); session.connect(); ...
🌐
Codesandscripts
codesandscripts.com › 2014 › 10 › java-program-to-execute-shell-scripts-on-remote-server.html
Java program to execute shell scripts on remote server
October 9, 2014 - If you want to execute shell scripts on remote server and get output with the help of your java program then you are at right place. In this tutorial we will be using Java secure channel ( Jsch ) to log on to remote server, execute the shell script and capture the output.
🌐
Myitlearnings
myitlearnings.com › java-code-to-run-a-remote-script-on-remote-host-using-ssh
Java code to run a remote script on remote host using SSH - My IT Learnings
February 17, 2016 - // 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 = channelExe
Find elsewhere
🌐
Spiceworks
community.spiceworks.com › programming & development
How to call Linux shell scripts from java remotely - Programming & Development - Spiceworks Community
December 29, 2009 - "I have a shell script in remote linux machine (dir: ctl_files/kfg). I want to call this from local machine (windows). How I can do that? I have written below code: package com.test; import java.io.IOException; public class CallShellScripts { public static void main(String args){ String command = {“ssh”, “username@hostserver”, “/ctl_files/kfg/test.ksh”}; try { final Process process = Runtime.getRuntime().exec(command); System.out.println(“End”); } catch (IOException e) { // TODO Auto-generated c...
Top answer
1 of 4
3

I don't know anything about Java, but I can show you a proof of concept. Say we have localfile.txt:

Here is the local file.

and on the remote machine, we have remote.sh:

#!/bin/bash
cat /dev/stdin

Note that the script on the remote machine invokes a program which reads from stdin. Then pass the contents of localfile.txt to your ssh command:

user@local:~$ cat localfile.txt | ssh user@remote remote.sh
Here is the local file.

Your Java program is trying to read a file which does not exist on the remote machine. I guess you could try to mimic a local file.

Change remote.sh to:

#!/bin/bash
cat "$@"

and invoke it with

user@local:~$ cat localfile.txt | ssh user@remote 'remote.sh <(cat /dev/stdin)'
Here is the local file.

I think it would be easier to change that part in your Java program to read from stdin.

I guess things might get messy if localfile.txt contains anything that might be interpreted by the shell as expandable (such as *), but that's for you to figure out.

2 of 4
2

The problem is that the shell redirection (<) sends the file over the ssh tunnel. And the Java class is expecting not the file, but a string with the "filename" of a local file that will be read with a FileReader.

Instead of passing the filename to the FileReader, read from the standard input.

InputStreamReader isReader = new InputStreamReader(System.in);
BufferedReader iR  = new BufferedReader (isReader);

Used this as a reference: https://stackoverflow.com/questions/5724646/how-to-pipe-input-to-java-program-with-bash

Now your class will be:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;

public class ReadFirstLine 
{
    public static void main(String[] args) throws Exception 
    {
       String filename = args[0];
       System.out.println(filename);

       //BufferedReader iR  = new BufferedReader (new FileReader(filename));
       InputStreamReader isReader = new InputStreamReader(System.in);
       BufferedReader iR  = new BufferedReader (isReader);

       BufferedWriter oW = new BufferedWriter(new OutputStreamWriter(System.out));

       //outputWriter.write(iR.readLine());
       System.out.println(iR.readLine());

       iR.close();
       oW.close();
    }
}

But for this task I would definitely use instead:

head -1 filename.txt

:)

🌐
Flowable
forum.flowable.org › t › execute-shell-scripts-at-a-remote-host › 536
Execute Shell Scripts at a Remote Host - Flowable
May 5, 2017 - Hi I need to execute few Shell Scripts which live at a remote machine. As of now, am using a third party library (JSch). I just got introduced to Shell-Task. Can I use this to connect to a remote host and then execute …
🌐
Hjortsberg
hjortsberg.org › notes › Writing-a-remote-shell-in-Java.html
Writing a remote shell in Java - hjortsberg.org
January 19, 2020 - If the remote shell is given the parameter to start bash it is possible for the client to write commands to the bash command i.e. basically run any command.
🌐
Coderanch
coderanch.com › t › 574033 › java › Java-run-shell-script-Unix
Using Java to run shell script on Unix server installed on remote macine (Sockets and Internet Protocols forum at Coderanch)
April 19, 2012 - I need to run a unix script on remote machine by supplying two arguments, please suggest. ... Nipun Bahr wrote: Can we do the same using Process Builder? Since ProcessBuilder, like Runtime.exec, can only execute processes locally, that will only work if you have a process such as ssh that you can invoke, so you can invoke that process and tell it to run the remote command.
🌐
Stack Overflow
stackoverflow.com › questions › 22602529 › executing-remote-shell-commands-in-java
Executing remote shell commands in Java - Stack Overflow
So that you can give /dev/null redirect in the shell script instead of giving the set of commands in the program itself – SachinJ Mar 24 '14 at 10:20 ... Why do Western countries seem to be less efficient than Asian countries in fighting against COVID-19? Prevent unnecessary increase of line spacing after inline equation ... Short selling banned in Italy for 3 months. Am I affected with my Short ETF investments? How can you build a model of tetrahedral coordination from objects found at home?
🌐
Baeldung
baeldung.com › home › java › core java › how to run a shell command in java
How to Run a Shell Command in Java | Baeldung
January 8, 2024 - Here, we created a new sub-process with .newSingleThreadExecutor() and then used .submit() to run our Process containing the shell commands. Additionally, .submit() returns a Future object we utilize to check the result of the process. Also, make sure to call the .get() method on the returned object to wait for the computation to complete. If you are running the above code from a main method, be sure to call shutdown on the executorService object or the code will never stop.
🌐
Netjstech
netjstech.com › 2016 › 10 › how-to-run-shell-script-from-java-program.html
How to Run a Shell Script From Java Program | Tech Tutorials
You are trying to run shell script on a Windows system! What do you expect ??? Though there are ways to run sh from widows but that will require some work. You can't just rum a sh file from windows command line. Delete ... If you are using Windows replace "sh" with "cmd". The terminal of is "powershell" or "cmd". "sh", "/bin/bash", "/usr/bin/python" for other kinds of scripts.ReplyDelete ... This method works fine when I try to execute on local.
🌐
Oracle
forums.oracle.com › ords › apexds › post › how-to-execute-remote-server-shell-script-using-java-progra-3077
how to execute remote server shell script using java program. - Oracle Forums
October 3, 2008 - how do i call (Execute) a shell script which is on remote linux server from my local (windows server) using normal java program Edited by: java_dev_08 on Oct 3, 2008 5:24 AM