你可以嘗試使用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);
}
}
你不會說'這不是working'得到任何幫助。什麼不工作?代碼在哪裏?你如何執行命令? – 2012-02-14 12:31:37
考慮編輯你的問題,以包含你的java上下文中的行,以及(更重要的)任何你可以捕獲的錯誤信息。 java中的調用返回失敗狀態嗎?你能否將shell調試嵌入到上面的命令中,即'set -vx; sshpass ...'。你的JAVA和你運行shell代碼的終端有相同的PATH嗎?考慮添加'echo $ PATH; set -vx; sshpass ...來驗證PATH是正確的。祝你好運。 – shellter 2012-02-14 14:13:57