java中可以调用本地脚本,也可以远程调用shell脚本,但是java调用远程脚本不安全,一般不这么做,那该怎么调用呢?
建议在本地写个脚本调用远程脚本,在java程序中调用本地脚本,具体代码:
private int execShell(String shellPath, String... params) {
StringBuilder command = new StringBuilder(shellPath).append(" ");
for (String param : params) {
command.append(param).append(" ");
}
BufferedReader br = null;
StringBuilder sb = null;
try {
Process process = Runtime.getRuntime().exec(command.toString());
process.waitFor();
br = new BufferedReader(new InputStreamReader(process.getInputStream()));
sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
LOG.error("execShell() error, shellPath: {}, params: {}", shellPath, params, e);
return -2;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "".equals(sb.toString()) ? 0 : Integer.parseInt(sb.toString());
}
注意:如果脚本执行成功,process.waitFor()会返回0状态码;如果脚本执行出错,本根据不同的错误返回不同的状态码,此时需要使用流获取到脚本返回的状态