3

I am trying to run a shell script on a remote server using a JAVA API. The remote server has authentication , so i have to pass my username and password to login to it. I do not have the rights on these machines (neither source nor destination) to install 'sshpass' , in case you were going to give that solution.

What is the best way to do this?

8
  • Are you restricted only to the standard JDK? Commented Apr 4, 2016 at 16:50
  • yes i am using jdk 8. Commented Apr 4, 2016 at 16:55
  • And is this over ssh based upon your comment about sshpass? IMHO, the best way to invoke a script on a remote machine is to use JSch. We use JSch at work all the time. If writing from scratch, there are a lot of things to consider. So, again, are you limited only to the classes in the standard JDK, or can you use an external library? Commented Apr 4, 2016 at 17:01
  • oh, yes i can use an external library. Can you share some sample code for this? Commented Apr 4, 2016 at 17:03
  • will this example suffice. looked up jsch Commented Apr 4, 2016 at 17:07

2 Answers 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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.