首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 透過 shell 指令獲取 Linux 伺服器狀態(CPU、記憶體、磁碟、負載)

     編輯:PHP 綜合知識

核心思路

利用 popen() 執行系統指令(top、df、date),解析輸出文字取得關鍵指標,封裝為函式回傳陣列。

完整函式程式碼

<?php
function get_server_status() {
    // 1. CPU / Memory / Tasks (top 取兩次樣本,第二次較準)
    $fp = popen('top -b -n 2 | grep -E "^(Cpu|Mem|Tasks)"', 'r');
    $out = '';
    while (!feof($fp)) { $out .= fread($fp, 1024); }
    pclose($fp);
    $lines = explode("\n", $out);
    // 取第 2 次採樣的 3 行 (索引 3,4,5)
    $taskArr = explode(',', $lines[3]);
    $cpuArr  = explode(',', $lines[4]);
    $memArr  = explode(',', $lines[5]);

    $tasks_running = (int) trim(str_replace('running', '', $taskArr[1]));
    $cpu_usage     = (float) trim(str_replace(['Cpu(s): ', '%us'], '', $cpuArr[0]));

    $mem_total = (int) trim(str_replace(['Mem: ', 'k total'], '', $memArr[0]));
    $mem_used  = (int) trim(str_replace('k used', '', $memArr[1]));
    $mem_usage = $mem_total ? round(100 * $mem_used / $mem_total, 2) : 0;

    // 2. 磁碟使用率 (根分區)
    $fp = popen("df -lh | grep -E '^(/)'", 'r');
    $df = fread($fp, 1024);
    pclose($fp);
    $df = preg_replace('/\s+/', ' ', trim($df));
    $parts = explode(' ', $df);
    $disk_avail = (float) trim(str_replace('G', '', $parts[3]));
    $disk_usage = (float) trim(str_replace('%', '', $parts[4]));

    // 3. 偵測時間
    $fp = popen('date +"%Y-%m-%d %H:%M"', 'r');
    $detect_time = trim(fread($fp, 1024));
    pclose($fp);

    return [
        'cpu_usage'     => $cpu_usage,
        'mem_usage'     => $mem_usage,
        'disk_avail_gb' => $disk_avail,
        'disk_usage_pct'=> $disk_usage,
        'tasks_running' => $tasks_running,
        'detect_time'   => $detect_time,
    ];
}

使用範例

<?php
$status = get_server_status();
echo "CPU: {$status['cpu_usage']}%\n";
echo "Memory: {$status['mem_usage']}%\n";
echo "Disk Free: {$status['disk_avail_gb']} GB ({$status['disk_usage_pct']}% used)\n";
echo "Running Tasks: {$status['tasks_running']}\n";
echo "Time: {$status['detect_time']}\n";

注意事項與改進方向

  • 權限:PHP-FPM 執行用戶需有執行 top、df 權限(通常預設即有)。
  • 效能:top -n 2 會阻塞約 2 秒,高頻呼叫會影響效能。建議:
    • 寫入快取(Redis/檔案)5~10 秒更新一次。
    • 或改用 /proc/stat、/proc/meminfo 直接讀取(純 PHP 解析,無阻塞)。
  • 跨平台:top 輸出格式在不同 Linux 發行版可能略有差異,建議針對目標 OS 測試正則。
  • 安全:避免直接將用戶輸入傳入 popen,防止命令注入。
  • 擴充:可加入網卡流量(cat /proc/net/dev)、負載平均(uptime 或 /proc/loadavg)。

替代方案:純 PHP 讀取 /proc

// CPU 使用率(簡易版,需兩次採樣計算差值)
$stat1 = file('/proc/stat')[0]; sleep(1); $stat2 = file('/proc/stat')[0];
// 解析 user/nice/system/idle... 計算佔用率

純 PHP 解析 /proc 避免 popen 開銷,適合高頻監控 Agent。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved