/**
* 执行Shell脚本
* 原文链接:https://blog.csdn.net/zhang_yanchao/java/article/details/80811881
*
* @param filePath 脚本文件地址
* @param param 输入参数
* @return 返回值
*/
public static String execShell(String filePath, String param) {
try {
String result = "";
String[] command = {filePath, param};
Process ps;
if (param == null) {
//执行无参数的脚本
ps = Runtime.getRuntime().exec(filePath);
} else {
//执行带参数的脚本
ps = Runtime.getRuntime().exec(command);
}
int exitValue = ps.waitFor();
//当返回值为0时表示执行成功
if (0 != exitValue) {
throw new AppException("返回代码=" + exitValue);
}
//只能接收脚本echo打印的数据,并且是echo打印的最后一次数据,如果想打印所有数据,可以参考本篇文章的脚本编写
BufferedInputStream in = new BufferedInputStream(ps.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = br.readLine()) != null) {
log.info("脚本返回的数据如下: " + line);
result = line;
}
in.close();
br.close();
return result;
} catch (Exception ex) {
log.info("执行shell脚本失败,错误信息:" + ex);
throw new AppException("执行shell脚本失败,错误信息:" + ex.getMessage());
}
}
无权限 Cannot run program error=13 Permission denied
Process.waitFor()的返回值含义