1. 程式人生 > >java呼叫shell指令碼,解決傳參和許可權問題

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();
        }
    }