我有一个bash脚本,它使用sshpass和ssh自动登录到不同的机器和触发器命令。当从命令行触发时,bash脚本运行良好,但是当从java应用程序调用它时,它无法继续。
sshpass -p 'password' ssh user@XXX.XXX.XXX.XXX './SleepDisplay && exit'
bash脚本做了很多其他事情,我无法直接在java中实现ssh登录。我似乎无法弄明白,为什么它会失败。除了ssh之外的所有东西都运行良好。
答案 0 :(得分:1)
首先打开shell并执行命令。尝试以下内容:
String COMMAND = "sshpass -p 'password' ssh user@XXX.XXX.XXX.XXX './SleepDisplay && exit'";
String[] SHELL_COMMAND = { "/bin/sh", "-c", COMMAND };
...
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(SHELL_COMMAND);
希望我能给你一个有用的提示。
答案 1 :(得分:1)
通过Runtime.exec()
执行命令时,第一个元素是可执行文件,然后所有其他参数将在数组的其余部分单独传递。< / p>
但是你(可能)将整个linux 命令作为可执行文件传递,但这不起作用。
试试这个:
String[] cmdarray = {"sshpass", "-p", "'password'", "ssh", "user@XXX.XXX.XXX.XXX", "'./SleepDisplay && exit'"};
Runtime.getRuntime().exec(cmdarray);
答案 2 :(得分:0)
您可以尝试使用ganymed-ssh2
java库,它可以让您使用java执行和执行shell脚本等等...
下面显示了使用此库的示例:
{
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);
}
}