Java执行外部Linux命令/程序,并获取输出,以及解决管道、重定向命令无法执行的坑

2020-12-28 1593点热度 0人点赞 0条评论

Java执行外部命令/程序,获取输出,可能是错误流,也可能是标准输出流,可以根据需要区分开来输出,我目前是混在一起输出了,

private static String executeCommand() {
        StringBuilder sb = new StringBuilder();

        try {
            Process proc = Runtime.getRuntime().exec("java -version");
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

            // Read the output from the command
            String s = null;
            while ((s = stdInput.readLine()) != null) {
                sb.append(s).append("\n");
            }

            // Read any errors from the attempted command
            while ((s = stdError.readLine()) != null) {
                sb.append(s).append("\n");
            }
        } catch (Exception e) {
            sb.append(e.getMessage());
        }
        return sb.toString().trim();
}

另外发现执行管道命令或者重定向命令的时候,提示无法执行,例如执行 ps aux|grep java echo 'hello'>/opt/test.txt

可以修改如下解决

Process proc = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", "ps aux|grep java"});

Python下执行外部命令并获得输出,请看:https://blog.terrynow.com/2021/06/07/python-exec-command-and-get-output/

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论