利用 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";
top、df 權限(通常預設即有)。top -n 2 會阻塞約 2 秒,高頻呼叫會影響效能。建議:
/proc/stat、/proc/meminfo 直接讀取(純 PHP 解析,無阻塞)。top 輸出格式在不同 Linux 發行版可能略有差異,建議針對目標 OS 測試正則。popen,防止命令注入。cat /proc/net/dev)、負載平均(uptime 或 /proc/loadavg)。// CPU 使用率(簡易版,需兩次採樣計算差值)
$stat1 = file('/proc/stat')[0]; sleep(1); $stat2 = file('/proc/stat')[0];
// 解析 user/nice/system/idle... 計算佔用率
純 PHP 解析 /proc 避免 popen 開銷,適合高頻監控 Agent。