我找到了一個很好的提示來解決這個問題閱讀nohup維基百科頁面。合併nohup和ssh需要將stdin/std [out | err]重定向。
如果您的服務器沒有在/etc/sudoers
Defaults requiretty
,你可以簡單地使用:
sess.execCommand("nohup sudo <yourCommand> 2>&1 >nohup.out </dev/null &");
整個代碼:
import ch.ethz.ssh2.*
String hostname = "localhost";
String username = "gsus";
File keyfile = new File("/home/gsus/.ssh/id_rsa");
String keyfilePass = "";
try {
Connection conn = new Connection(hostname);
conn.connect();
boolean isAuthenticated=conn.authenticateWithPublicKey(username,keyfile,keyfilePass);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
Session sess=conn.openSession();
//Don't use this
//sess.requestDumbPTY();
sess.execCommand("nohup sudo ping -c 100 www.yahoo.com 2>&1 >nohup.out </dev/null &");
sess.close();
conn.close();
}
catch ( IOException e) {
e.printStackTrace(System.err);
System.exit(2);
}
相反,如果你的服務器/etc/sudoers
文件包含Defaults requiretty
(@ user5222688)你有使用開關session.startShell()
import ch.ethz.ssh2.*
String hostname = "localhost";
String username = "gsus";
File keyfile = new File("/home/gsus/.ssh/id_rsa");
String keyfilePass = "";
try {
Connection conn = new Connection(hostname);
conn.connect();
boolean isAuthenticated=conn.authenticateWithPublicKey(username,keyfile,keyfilePass);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
Session sess=conn.openSession();
sess.requestPTY("xterm");
sess.startShell();
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader input = new BufferedReader(new InputStreamReader(stdout));
OutputStream out = sess.getStdin();
out.write("nohup sudo <yourCommand> 2>&1 >nohup.out </dev/null &\n".getBytes());
out.flush();
while (!input.readLine().contains("stderr")) {
//Simply move on the stdout of the shell till our command is returned
}
sess.close();
conn.close();
}
catch (IOException e) {
e.printStackTrace(System.err);
System.exit(2);
}
越來越近......但我在我的stderr中得到了這個; 'sudo:對不起,你必須有一個tty來運行sudo' – user5222688
嘗試從服務器的/ etc/sudoers(''sudo visudo -f/etc/sudoers'')中刪除''Defaults requiretty'' –
不幸的是,不是一個選項... – user5222688