使用“sudo"执行 linux shell 命令使用java,无需输入所需密码

2022-01-22 00:00:00 sudo cmd passwords java

您好,我正在使用 ganymed-ssh2 java 库在 linux 工作站中成功执行远程命令.

Hi I'm using ganymed-ssh2 java library to execute remote commands in linux workstation with success.

但现在有一种情况,我需要执行一个命令,但这需要我输入一些密码……比如:

But now there is a situation where I need to execute a command but this require that i put some password...like:

sudo /usr/bin/some_process
please enter your password:  

我以前是这样实现远程cmd执行的:

I used to implement remote cmd execution in this way:

Session sess = conn.openSession();

sess.execCommand("uname -a && date && uptime && who");

System.out.println("Here is some information about the remote host:");

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


System.out.println("ExitCode: " + sess.getExitStatus());

sess.close();

conn.close();

恐怕不能用这个库执行需要密码的命令.

I'm afraid that it's not possible to execute commands that require a password with this library.

有人可以给我一个解决方案或替代方案来允许这个???

Someone could give me a solution or alternative to allow this ???

谢谢!

推荐答案

假设有一个 sess.getStdin(),你应该能够通过管道输入密码到 sudo 命令.

assuming there is a sess.getStdin(), you should be able to pipe in a password to the sudo command.

相关文章