个人博客原文地址:http://www.ltang.me/2016/10/23/java-call-shell/
之前做文档站点的时候有一个需求,做一个在线部署页面,能够通过页面上点点点就自动部署远程服务器上的服务,并且看到部署日志。简单的思路就是,页面通过websocket连接到java后台,java代码调用shell脚本执行发布操作,获取输出,并通过websocket将输出内容返回页面。
Runtime runtime = Runtime.getRuntime();
Process process;
BufferedReader br = null;
BufferedWriter wr = null;
try {
process = runtime.exec("//要执行的命令");
br = new BufferedReader(new InputStreamReader(process.getInputStream()));
wr = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
String inline;
while ((inline = br.readLine()) != null) {
if (!inline.equals("")) {
inline = inline.replaceAll("<", "<").replaceAll(">", ">");
session.getBasicRemote().sendText(inline); //返回给页面
if (inline.endsWith("发布到服务器?[Y/N]:")) {
wr.write("y"); //自动输入y
wr.newLine();
wr.flush();
session.getBasicRemote().sendText("y");
}
} else {
session.getBasicRemote().sendText("\n"); //换行
}
}
br.close();
br = new BufferedReader(new InputStreamReader(process.getErrorStream())); //错误信息
while ((inline = br.readLine()) != null) {
if (!inline.equals(""))
session.getBasicRemote().sendText("<font color='red'>" + inline + "</font>");
else
session.getBasicRemote().sendText("\n");
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
session.getBasicRemote().sendText("<font color='red'>" + e.getMessage() + "</font>");
} finally {
if (br != null)
br.close();
if (wr != null)
wr.close();
session.getBasicRemote().sendText("End.");
}