' nohup mycommand&'通过Java代码

时间:2015-10-07 09:32:40

标签: java bash ssh nohup

我正在尝试使用Ganymed-SSH2(ch.ethz.ssh2)运行以下命令:

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()(但这不会给我所需的结果),该命令可通过&方法运行,但&没有任何结果。< / p>

任何想法出了什么问题?

(注意:sudo不需要密码)

1 个答案:

答案 0 :(得分:1)

我在阅读nohup维基百科页面时找到了解决此问题的良好提示。结合nohup和ssh需要重定向stdin / std [out | err]。

如果您的服务器在Defaults requiretty中没有/etc/sudoers,您只需使用:

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);
}