2015-10-07 28 views
1

我試圖運行使用Ganymed-SSH2(ch.ethz.ssh2)以下命令:「的nohup mycommand的&」通過Java代碼

nohup sudo mycommand & 

它,當我直接運行命令行工作,但沒有當我使用下面的Java代碼運行它時會發生。

Connection connection = new Connection(server); 
connection.connect(); 

if (!connection.authenticateWithPassword(userName, password)) { 
throw new IOException("Failed to authenticate with user " + userName + "on host: " + connection.getHostname()); 
    } 

Session session = connection.openSession(); 
session.requestDumbPTY(); 

session.execCommand("nohup sudo mycommand &"); 

session.close(); 
connection.close(); 

通過execCommand()方法的命令的工作,如果我排除&(但是這不會給我我需要的結果),但沒有與&有發生。

任何想法出了什麼問題?

(注:命令不需要密碼)

回答

1

我找到了一個很好的提示來解決這個問題閱讀nohup維基百科頁面。合併nohup和ssh需要將stdin/std [out | err]重定向。

如果您的服務器沒有在/etc/sudoersDefaults 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); 
} 
+0

越來越近......但我在我的stderr中得到了這個; 'sudo:對不起,你必須有一個tty來運行sudo' – user5222688

+0

嘗試從服務器的/ etc/sudoers(''sudo visudo -f/etc/sudoers'')中刪除''Defaults requiretty'' –

+0

不幸的是,不是一個選項... – user5222688