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.
-
1How does your java application establish that connection? What library are you using?GhostCat– GhostCat2019-01-09 09:44:31 +00:00Commented Jan 9, 2019 at 9:44
-
Use JSch to connect to your server via SSH and get a shell to execute commands on the server. See here for a code example: Shell.java.vanje– vanje2019-01-09 09:49:54 +00:00Commented Jan 9, 2019 at 9:49
3 Answers
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
sshconnection - Execute the script from that connection
You need to use a library like JSch, here's an example.
Comments
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();
}