萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> JSP 程式設計

JSP 調用 Linux Shell 腳本實戰:緩存清理自動化運維頁面

場景與架構

運維人員需定期清理緩存(如 Memcached),通過 JSP 頁面觸發 Shell 腳本,實現「一鍵清理」,避免登錄服務器操作。架構:

瀏覽器 → JSP (Runtime.exec) → Shell腳本 → nc 命令 → Memcached (flush_all) → 結果回顯

完整 JSP 實現代碼

<%@ page language="java" import="java.io.*" pageEncoding="UTF-8"%>
<%@ page contentType="text/html;charset=UTF-8"%>
<html>
<head>
    <title>緩存清理管理頁面</title>
    <style>
        body {font-family: '微軟雅黑', sans-serif; margin: 20px;}
        .btn {padding: 10px 20px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer;}
        .btn:hover {background: #0056b3;}
        pre {background: #f8f9fa; padding: 15px; border-radius: 4px; overflow-x: auto;}
        .success {color: #28a745;} .error {color: #dc3545;}
    </style>
</head>
<body>
    <h2>Memcached 緩存清理工具</h2>
    <form method="post">
        <input type="submit" name="execute" value="執行清理緩存" class="btn" />
    </form>
    <hr/>
    
    <%
        if (request.getParameter("execute") != null) {
            String scriptPath = "/opt/wzx/monitor.sh"; // 絕對路徑
            String[] cmd = {"/bin/sh", scriptPath};   // 顯式指定 Shell 解析器
            
            try {
                Process process = Runtime.getRuntime().exec(cmd);
                
                // 讀取標準輸出
                StringBuilder output = new StringBuilder();
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(process.getInputStream(), "UTF-8"))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        output.append(line).append("\n");
                    }
                }
                
                // 讀取錯誤輸出
                StringBuilder error = new StringBuilder();
                try (BufferedReader errReader = new BufferedReader(
                        new InputStreamReader(process.getErrorStream(), "UTF-8"))) {
                    String line;
                    while ((line = errReader.readLine()) != null) {
                        error.append(line).append("\n");
                    }
                }
                
                int exitCode = process.waitFor();
                
                if (exitCode == 0) {
                    out.println("<div class='success'><h4>✅ 執行成功 (Exit Code: 0)</h4></div>");
                } else {
                    out.println("<div class='error'><h4>❌ 執行失敗 (Exit Code: " + exitCode + ")</h4></div>");
                }
                
                if (output.length() > 0) {
                    out.println("<h5>標準輸出:</h5><pre>" + escapeHtml(output.toString()) + "</pre>");
                }
                if (error.length() > 0) {
                    out.println("<h5>錯誤輸出:</h5><pre class='error'>" + escapeHtml(error.toString()) + "</pre>");
                }
                
            } catch (Exception e) {
                out.println("<div class='error'><h4>❌ 異常: " + escapeHtml(e.getMessage()) + "</h4></div>");
                e.printStackTrace();
            }
        }
    %>
    
    <!-- 工具方法:防止輸出中包含 HTML 標籤導致 XSS -->
    <%! 
        private String escapeHtml(String input) {
            return input.replace("&", "&amp;")
                        .replace("<", "&lt;")
                        .replace(">", "&gt;")
                        .replace("\"", "&quot;")
                        .replace("'", "'");
        }
    %>
</body>
</html>

Shell 腳本 monitor.sh

#!/bin/bash
# /opt/wzx/monitor.sh
# 功能:清理 Memcached 緩存
# 依賴:nc (netcat-openbsd)

MEMCACHED_HOST="192.168.10.73"
MEMCACHED_PORT="11211"

echo "[$(date '+%Y-%m-%d %H:%M:%S')] 開始清理緩存: $MEMCACHED_HOST:$MEMCACHED_PORT"

# 發送 flush_all 命令
echo "flush_all" | nc -w 5 $MEMCACHED_HOST $MEMCACHED_PORT

if [ $? -eq 0 ]; then
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] ✅ 緩存清理命令發送成功"
    exit 0
else
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] ❌ 緩存清理失敗,請檢查網絡/服務狀態"
    exit 1
fi

關鍵安全與穩健性加固

風險點解決方案
命令注入使用 String[] cmd 數組形式 exec(cmd),避免字符串拼接;參數白名單校驗
權限最小化腳本文件屬主為應用用戶,權限 700;sudoers 僅允許無密碼執行特定腳本
超時控制Shell 內 nc -w 5;Java 端可用 Process.waitFor(long, TimeUnit) (Java 8+)
輸出流阻塞**必須**同時消費 stdout/stderr,否則管道填滿導致進程掛起
編碼問題顯式指定 InputStreamReader(..., "UTF-8"),匹配腳本輸出編碼
身份認證**生產環境必須**添加登錄驗證、角色授權、操作審計日志
CSRF 防護表單添加 <input type="hidden" name="csrfToken" value="${sessionScope.csrfToken}" />

現代化替代方案

  • Actuator Endpoint:Spring Boot Actuator 暴露 /actuator/caches 管理端點
  • 定時任務:Quartz / Spring @Scheduled 定時自動清理,無需人工干預
  • 運維平台:Jenkins / Ansible / SaltStack 統一編排,Web 界面僅做觸發與展示
  • Kubernetes:kubectl exec 或 Sidecar 容器管理緩存
copyright © 萬盛學電腦網 all rights reserved