運維常需清理快取、重啟服務等操作,若能透過 Web 頁面觸發 Shell 腳本,將大幅降低人工成本。本文示範 JSP 以 Runtime.getRuntime().exec() 呼叫 Linux 腳本,並即時讀取標準輸出顯示於頁面。
<%@ page import="java.io.*" pageEncoding="UTF-8" %>
<html><body>
<%
String script = "/opt/wzx/monitor.sh"; // 絕對路徑,確保權限
try {
Process proc = Runtime.getRuntime().exec(new String[]{"sh", script});
// 捕獲標準輸出
BufferedReader br = new BufferedReader(
new InputStreamReader(proc.getInputStream(), "UTF-8"));
String line;
proc.waitFor(); // 等待結束(或改非阻塞輪詢)
while ((line = br.readLine()) != null) {
out.print(line);
out.print("<br/>");
}
br.close();
} catch (Exception e) {
e.printStackTrace(out);
}
%>
</body></html>
monitor.sh#!/bin/bash
echo 'flush_all' | nc 192.168.10.73 11211 # 清 Memcached
echo "Cache flushed at $(date)"
記得 chmod +x monitor.sh,並確保執行 JSP 的使用者(如 tomcat)對腳本有執行權限。
exec 不會載入 Shell 環境變數,命令與腳本皆用完整路徑。exec(new String[]{"sh", script}) 避免空白/特殊字元解析問題。getInputStream() 與 getErrorStream()**(建議用兩條執行緒),否則管道塞滿導致進程卡死。waitFor() 卡住請求執行緒,改用 CompletableFuture 或排程器非同步執行,頁面回傳任務 ID,前端輪詢狀態。InputStreamReader(proc.getInputStream(), "UTF-8") 明確指定編碼,防止中文亂碼。