繁体   English   中英

使用ProcessBuilder运行shell脚本

[英]Running a shell script using ProcessBuilder

我正在尝试使用Java和ProcessBuilder运行脚本。 当我尝试运行时,收到以下消息:error = 2,没有这样的文件或目录。

我不知道我做错了什么,但这是我的代码(ps:我试图只执行没有参数的脚本,错误是相同的:

String[] command = {"/teste/teste_back/script.sh, "+argument1+", "+argument+""};
ProcessBuilder p = new ProcessBuilder(command);

    try {  

        // create a process builder to send a command and a argument
        Process p2 = p.start(); 
        BufferedReader br = new BufferedReader(new InputStreamReader(p2.getInputStream()));
        String line;

        log.info("Output of running " + command + " is: ");
        System.out.println("Output of running " + command + " is: ");
        while ((line = br.readLine()) != null) {
            log.info(line);
        }

    }  

尝试更换

String[] command = {"/teste/teste_back/script.sh, "+argument1+", "+argument+""};

String[] command = {"/teste/teste_back/script.sh", argument1, argument};

有关更多信息,请参阅ProcessBuilder

ProcessBuilder(String ...命令)

使用指定的操作系统程序和参数构造流程构建器。

除非你的script.sh名字中有逗号,否则就是错误:

String[] command = {"/teste/teste_back/script.sh" , argument1, argument};

您可以使用ProcessBuilder定义方法。

public static Map execCommand(String... str) {
    Map<Integer, String> map = new HashMap<>();
    ProcessBuilder pb = new ProcessBuilder(str);
    pb.redirectErrorStream(true);
    Process process = null;
    try {
        process = pb.start();
    } catch (IOException e) {
        e.printStackTrace();
    }

    BufferedReader reader = null;
    if (process != null) {
        reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    }

    String line;
    StringBuilder stringBuilder = new StringBuilder();
    try {
        if (reader != null) {
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        if (process != null) {
            process.waitFor();
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    if (process != null) {
        map.put(0, String.valueOf(process.exitValue()));
    }

    try {
        map.put(1, stringBuilder.toString());
    } catch (StringIndexOutOfBoundsException e) {
        if (stringBuilder.toString().length() == 0) {
            return map;
        }
    }
    return map;
}

您可以调用该函数来执行shell命令或脚本

String cmds = "ifconfig";
String[] callCmd = {"/bin/bash", "-c", cmds};
System.out.println("exit code:\n" + execCommand(callCmd).get(0).toString());
System.out.println();
System.out.println("command result:\n" + execCommand(callCmd).get(1).toString());

暂无
暂无

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

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