1. java 執(zhí)行shell
java 通過 Runtime.getRuntime().exec() 方法執(zhí)行 shell 的命令或 腳本,exec()方法的參數(shù)可以是腳本的路徑也可以是直接的 shell命令
代碼如下(此代碼是存在問題的。完整代碼請(qǐng)看2):
/** * 執(zhí)行shell * @param execCmd 使用命令 或 腳本標(biāo)志位 * @param para 傳入?yún)?shù) */ 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. 遇到的問題和解決
- 傳參問題,當(dāng)傳遞的參數(shù)字符串中包含空格時(shí),上邊的方法會(huì)把參數(shù)截?cái)啵J(rèn)為參數(shù)只到空格處。
- 解決:將shell 命令或腳本 和參數(shù) 放在一個(gè) 數(shù)組中,然后將數(shù)組傳入exec()方法中。
- 權(quán)限問題,當(dāng)我們用 this.getClass().getResource("/callShell.sh").getPath() 獲取腳本位置的時(shí)候取的 target 下的shell腳本,這時(shí)候 shell 腳本是沒有執(zhí)行權(quán)限的。
- 解決:在執(zhí)行腳本之前,先賦予腳本執(zhí)行權(quán)限。
完整的代碼如下
/** * 解決了 參數(shù)中包含 空格和腳本沒有執(zhí)行權(quán)限的問題 * @param scriptPath 腳本路徑 * @param para 參數(shù)數(shù)組 */ private void execShell(String scriptPath, String ... para) { try { String[] cmd = new String[]{scriptPath}; //為了解決參數(shù)中包含空格 cmd=ArrayUtils.addAll(cmd,para); //解決腳本沒有執(zhí)行權(quán)限 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"); } //執(zhí)行結(jié)果 String result = sb.toString(); } catch (Exception e) { e.printStackTrace(); } }
源碼位置:
https://github.com/527515025/JavaTest/tree/master/src/main/java/com/us/callShell
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)服務(wù)器之家的支持。