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
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對服務器之家的支持。