简体   繁体   中英

Executing the Unix script from Java

I am trying to run a unix shell script from java which is available at a particular directory in unix server. This script accepts parameters. I was able to establish SFTP connection and successfully reached to the directory which is holding the shell script. How do i run this script and how to pass parameters? Got few references at https://netjs.blogspot.com/2016/10/how-to-run-shell-script-from-java-program.html but here the script is available at local system. In my case the script is on server and also accepts parameters.

SFTP is a file transfer protocol ( Secure File Transfer Protocol ). It lets you transfer the files to and from the server. However, it doesn't let you execute any script on the remote server as that's not what it's designed to do.

If you want to execute a script in remote server then you need to:

  • Establish an ssh connection
  • Execute the script from that connection

You need to use a library like JSch , here's an example.

Another way is execute command over SSH. You create a new script in your localhost (my sample is test.sh ) with content as below, and now you can execute it like the way you get from your references.

ssh user@server "sh your-shell-script-in-server.sh"

Read more at https://www.cyberciti.biz/faq/unix-linux-execute-command-using-ssh/

Java source:

    String[] cmd = new String[] { "/bin/sh", "test.sh" };
    try {
        Process pr = Runtime.getRuntime().exec(cmd);
        int rs = pr.waitFor();
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }

Your Java function is based on the Runtime object. I'm not sure but I think you can't get the Runtime object of a remote machine, therefore you'll need to put the CLASS-file on that remote machine and launch it up there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM