Java executes shell script to pass parameters and permission problems

1. java execute shell

Java executes shell commands or scripts through the Runtime.getRuntime().exec() method. The parameter of the exec() method can be the path of the script or a direct shell command

The code is as follows (this code is problematic. Please see 2 for the complete code):


 /**
     * 执行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. Problems encountered and solutions

  • The parameter passing problem, when the passed parameter string contains spaces, the above method will truncate the parameter, and the default is that the parameter only goes to the space.
  • Solution: Put the shell command or script and parameters in an array, then pass the array into the exec() method.

  • Permission problem, when we use  this.getClass().getResource("/callShell.sh").getPath() the shell script under the target that we get when we get the script location, the shell script has no execution permission at this time.

  • Solution: Before executing the script, give the script execution permission.

The complete code is as follows

 /**
     * 解决了 参数中包含 空格和脚本没有执行权限的问题
     * @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();
        }
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325427111&siteId=291194637