Reputation: 2062
I have a bash script, that uses sshpass and ssh to autologin to different machine and trigger command. The bash script works well, when triggered from the command line, but when it is called from java application, it fails to proceed.
sshpass -p 'password' ssh [email protected] './SleepDisplay && exit'
The bash script does a lot of other things and I have no way to implement the ssh login directly in java. I don't seem to be able to figure out, why it fail. Everything but the ssh runs well.
Upvotes: 2
Views: 5423
Reputation: 1282
You could try to use the ganymed-ssh2
java library, it's let you able to perform and execute shell scripts and so on using java...
Below is showed an example using this library:
{
String hostname = "127.0.0.1";
String username = "joe";
String password = "joespass";
try
{
/* Create a connection instance */
Connection conn = new Connection(hostname);
/* Now connect */
conn.connect();
/* Authenticate.
* If you get an IOException saying something like
* "Authentication method password not supported by the server at this stage."
* then please check the FAQ.
*/
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
/* Create a session */
Session sess = conn.openSession();
// here execute which command separate for ";"
sess.execCommand("uname -a && date && uptime && who");
System.out.println("Here is some information about the remote host:");
/*
* This basic example does not handle stderr, which is sometimes dangerous
* (please read the FAQ).
*/
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true)
{
String line = br.readLine();
if (line == null)
break;
System.out.println(line);
}
/* Show exit status, if available (otherwise "null") */
System.out.println("ExitCode: " + sess.getExitStatus());
/* Close this session */
sess.close();
/* Close the connection */
conn.close();
}
catch (IOException e)
{
e.printStackTrace(System.err);
System.exit(2);
}
}
Upvotes: 0
Reputation: 6183
Open a shell first and execute the command. Try something like the following:
String COMMAND = "sshpass -p 'password' ssh [email protected] './SleepDisplay && exit'";
String[] SHELL_COMMAND = { "/bin/sh", "-c", COMMAND };
...
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(SHELL_COMMAND);
Hope I could give you a helpful hint.
Upvotes: 1
Reputation: 424993
When executing commands via Runtime.exec()
, the first element is the executable, then all other parameters are passed in separately in the rest of the array.
But you are (probably) passing the whole linux command in as the executable, which doesn't work.
Try this:
String[] cmdarray = {"sshpass", "-p", "'password'", "ssh", "[email protected]", "'./SleepDisplay && exit'"};
Runtime.getRuntime().exec(cmdarray);
Upvotes: 1