java调用shell脚本,解决传参和权限问题

1. java 执行shell

java 通过 Runtime.getRuntime().exec() 方法执行 shell 的命令或 脚本,exec()方法的参数可以是脚本的路径也可以是直接的 shell命令

代码如下(此代码是存在问题的。完整代码请看2):


 /**
     * 执行shell
     * @param execCmd 使用命令 或 脚本标志位
     * @param para 传入参数
     */
    private static void execShell(boolean execCmd, String... para) {
        StringBuffer paras = new StringBuffer();
        Arrays.stream(para).forEach(x -> paras.append(x).append(" "));
        try {
            String cmd = "", shpath = "";
            if (execCmd) {
                // 命令模式
                shpath = "echo";
            } else {
            //脚本路径
                shpath = "/Users/yangyibo/Desktop/callShell.sh";

            }
            cmd = shpath + " " + paras.toString();
            Process ps = Runtime.getRuntime().exec(cmd);
            ps.waitFor();

            BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            String result = sb.toString();
            System.out.println(result);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2. 遇到的问题和解决

  • 传参问题,当传递的参数字符串中包含空格时,上边的方法会把参数截断,默认为参数只到空格处。
  • 解决:将shell 命令或脚本 和参数 放在一个 数组中,然后将数组传入exec()方法中。

  • 权限问题,当我们用 this.getClass().getResource("/callShell.sh").getPath() 获取脚本位置的时候取的 target 下的shell脚本,这时候 shell 脚本是没有执行权限的。

  • 解决:在执行脚本之前,先赋予脚本执行权限。

完整的代码如下

 /**
     * 解决了 参数中包含 空格和脚本没有执行权限的问题
     * @param scriptPath 脚本路径
     * @param para 参数数组
     */
    private void execShell(String scriptPath, String ... para) {
        try {
            String[] cmd = new String[]{scriptPath};
            //为了解决参数中包含空格
            cmd=ArrayUtils.addAll(cmd,para);

            //解决脚本没有执行权限
            ProcessBuilder builder = new ProcessBuilder("/bin/chmod", "755",scriptPath);
            Process process = builder.start();
            process.waitFor();

            Process ps = Runtime.getRuntime().exec(cmd);
            ps.waitFor();

            BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            //执行结果
            String result = sb.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

源码位置:
https://github.com/527515025/JavaTest/tree/master/src/main/java/com/us/callShell

参考:http://www.jb51.net/article/61529.htm

猜你喜欢

转载自blog.csdn.net/u012373815/article/details/78771689