JAVA执行shell脚本并实时获取输出

之前做文档站点的时候有一个需求,做一个在线部署页面,能够通过页面上点点点就自动部署远程服务器上的服务,并且看到部署日志。简单的思路就是,页面通过websocket连接到java后台,java代码调用shell脚本执行发布操作,获取输出,并通过websocket将输出内容返回页面。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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("<", "&lt;").replaceAll(">", "&gt;");
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.");
}