Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中运行sshpass命令时未找到该命令_Java_Bash_Shell_Sh_Sshpass - Fatal编程技术网

在java中运行sshpass命令时未找到该命令

在java中运行sshpass命令时未找到该命令,java,bash,shell,sh,sshpass,Java,Bash,Shell,Sh,Sshpass,我试图运行一个命令,从远程地址内的文件读取字符串(我确信文件在那里),当我在bash上运行该命令时,该命令有效,但当我在java代码中运行它时,该命令无效 Runtime rt = Runtime.getRuntime(); String[] command; String line; try { command = new String[] {"sh", "-c", "\"sshpass " + "-p " + password + " ssh

我试图运行一个命令,从远程地址内的文件读取字符串(我确信文件在那里),当我在bash上运行该命令时,该命令有效,但当我在java代码中运行它时,该命令无效

    Runtime rt = Runtime.getRuntime();
    String[] command;
    String line;

    try {
        command = new String[] {"sh", "-c", "\"sshpass " + "-p " + password + " ssh " + user + "@" + ip + " 'cat " + file.getAbsolutePath() + "'\"" };

        Process mountProcess = rt.exec(command);

        mountProcess.waitFor();

        bufferedReader = new BufferedReader(new InputStreamReader(mountProcess.getInputStream()));
        while ((line = bufferedReader.readLine()) != null) {
            user_list.put(user, line);
        }
        bufferedReader.close();

        bufferedReader = new BufferedReader(new InputStreamReader(mountProcess.getErrorStream()));
        while ((line = bufferedReader.readLine()) != null) {
            LOGGER.debug("Stderr: " + line);
        }
        bufferedReader.close();
    } catch ...
我的用户列表中没有添加任何行(因此getInputStream中的行为null),我从代码中的记录器中得到以下错误:

Stderr: sh: 1: sshpass: not found
如果我在bash上使用完全相同的命令,它就会工作,并打印出我需要的字符串

sshpass -p password ssh remote@192.168.1.10 'cat /home/ID/ID'

有人知道为什么会这样吗?谢谢

我建议您不需要使用
sh
来包装您的命令。试一试

command = new String[] {"sshpass", "-p", password, "ssh", user + "@" + ip, "cat " + file.getAbsolutePath() };

如果需要使用
sh
,请从命令字符串中删除转义的双引号:将它们作为文字字符发送:

command = new String[] {
    "sh", 
    "-c", 
    String.format("sshpass -p %s ssh %s@%s 'cat %s'", password, user, ip, file.getAbsolutionPath())
};

如果您仍然得到“未找到命令”,那么您需要指定
sshpass
的完整路径,或者确保其目录位于您的路径中。

使用java执行此命令时,用户是tomcat8而不是root(在bash终端中使用时)

对我有效的解决方案包括一些标志:

String.format("/usr/local/bin/sshpass -p %s /usr/bin/ssh -q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no %s@%s 'cat %s'", password, user, ip, file.getAbsolutePath());

给出
sshpass的完整路径
考虑格式化我用完整路径“/usr/local/bin/sshpass”而不是“sshpass”尝试过的命令的字符串,我仍然有相同的错误起初,我尝试过这种方法,但如果我不使用“sh”—c,则会引发异常。我已经尝试过你的建议。如果没有双引号,我会收到以下错误消息:
Stderr:无法使用双引号创建目录“/usr/share/tomcat8/.ssh”。
使用String.format,与您描述的完全相同:
Stderr:/bin/sh:1:/usr/local/bin/sshpass-p password/usr/bin/sshremote@192.168.1.10“cat/home/ID/ID”:未找到