简体   繁体   English

Java中的sshpass给出错误:/ bin / sh:sshpass:找不到命令

[英]sshpass in Java gives error: /bin/sh: sshpass: command not found

I'm trying to execute a simple sshpass command in java: 我试图在Java中执行一个简单的sshpass命令:

String command = "sshpass -p password ssh user@host 'echo test' ";

ProcessBuilder pb = new ProcessBuilder("/bin/sh", "-c", command);
pb.inheritIO();
Process process = pb.start();
process.waitFor();

But the execution of command fails printing the following error on the console: 但是命令的执行无法在控制台上显示以下错误:

/bin/sh: sshpass: command not found

If I execute the command in the Terminal od my Mac OS, the command runs perfectly. 如果我在Mac OS的终端机中执行命令,该命令将完美运行。 (already installed sshpass via brew). (已通过brew安装sshpass)。

How to execute the command also in java? 如何在Java中也执行命令?

Thanks to @Thorbjørn Ravn Andersen, this is the right command (for Mac): 感谢@ThorbjørnRavn Andersen,这是正确的命令(对于Mac):

String command = "/usr/local/bin/sshpass -p password ssh user@host 'echo test' ";

You can find the right path executing the following command: 您可以找到执行以下命令的正确路径:

$ which sshpass

This is actually a Unix thing, not Java. 这实际上是Unix,而不是Java。 There are two things here: 这里有两件事:

  • By not giving the absolute path to sshpass , you rely on the shell to find it in $PATH 通过不提供sshpass的绝对路径,您可以依靠shell在$PATH找到它
  • You explicitly start a new shell, which - as it is non-interactive - does not load all the configuration files your interactive shell did. 您显式启动一个新的 Shell,因为它是非交互式的,所以不会加载您的交互式Shell所做的所有配置文件。 If the adding of /usr/local/bin to $PATH is not placed in an appropriate configuration file it will not be executed. 如果未将/usr/local/bin$PATH中,则不会将其添加到适当的配置文件中。 Full details available in the shell manual page. Shell手册页中提供了完整的详细信息。

By giving the absolute path you circumvent the lookup mechanism! 通过给出绝对路径,您可以绕过查找机制!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM