使用Java(Unix)中的Process Builder在一行中执行Shell脚本多个命令

问题描述 投票:0回答:2

我有一个要从Java执行的Shell脚本。

sudo su-用户名-c“ ssh -t remote_hostname df -k”

当您从命令提示符处运行时,此shell脚本运行良好。但是,当我使用流程生成器时,它不会返回任何内容。如果我执行以下操作:sudo su-用户名-c ssh -t remote_hostname; df -k

然后命令在我的本地计算机上而不是远程计算机上运行。

感谢任何反馈。

java代码处理p;

ExecutorService es = null;尝试{

p = Runtime.getRuntime()。exec(test1.sh);

[StreamGobbler sg =新的StreamGobbler(p.getInputStream(),System.out :: println());

es = Executors.newSingleThreadExecutor();

es.submt(sg);

int exitCode = p.waitfor();

断言exitCode == 0;

es.shutdown();

}抓住(....){}

java processbuilder
2个回答
0
投票

您正在尝试执行test1.sh。但是,test1.sh是什么?如果它是Shell脚本,通常是保存在某个地方,则需要将test1.sh作为File并将其内容传递给exec()方法。像这样:

public static void main(String[] args) throws IOException {
    Files.lines(new File("/Users/roberto/Desktop/demo/src/main/resources/test1.sh").toPath())
            .forEach(line -> {
                Process p = null;
                try {
                    p = Runtime.getRuntime().exec(line);
                    System.out.println(p.exitValue());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            })
    ;
}

或者您可以直接在exec()方法中运行命令:

public static void main(String[] args) throws IOException {
    Process p = Runtime.getRuntime().exec("sudo su - username -c \"ssh -t remote_hostname df -k\"");
    System.out.println(p.exitValue());
}

0
投票

Runtime.exec(String)不是外壳程序,特别是不像外壳程序一样解析和处理引号。欺骗:Why does Runtime.exec(String) work for some but not all commands?Whitespace in bash path with javaKeytool command does not work when invoked with Java

执行类似操作

String[] cmd = { "sudo", "su", "-", "username", "-c", "ssh -t remote_hostname df -k" };
// note the last element is a single Java String that does not _contain_ 
// any quote characters (which would be backslashed in Java source)
... Runtime.getRuntime().exec(cmd) ...

而且,当您运行-t时,您不需要df -k -它不执行任何特殊的输出处理。

© www.soinside.com 2019 - 2024. All rights reserved.