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

Linux 下 PHP 獲取伺服器狀態的簡潔實作(CPU、內存、磁碟、進程)

     編輯:PHP 相關知識

完整函數代碼

<?php
function get_used_status() {
    // 取得 top 輸出
    $fp = popen('top -b -n 2 | grep -E \"^(Cpu|Mem|Tasks)\"', 'r');
    $rs = '';
    while (!feof($fp)) { $rs .= fread($fp, 1024); }
    pclose($fp);
    $sys_info = explode(\"\\n\", $rs);

    $task_info = explode(',', $sys_info[3]);
    $cpu_info  = explode(',', $sys_info[4]);
    $mem_info  = explode(',', $sys_info[5]);

    $task_running = trim(trim($task_info[1], 'running'));
    $cpu_usage    = trim(trim($cpu_info[0], 'Cpu(s): '), '%us');

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

    // 磁碟
    $fp = popen('df -lh | grep -E \"^(/)\"', 'r');
    $rs = fread($fp, 1024);
    pclose($fp);
    $rs = preg_replace('/\\s{2,}/', ' ', $rs);
    $hd = explode(' ', $rs);
    $hd_avail = trim($hd[3], 'G');
    $hd_usage = trim($hd[4], '%');

    // 時間
    $fp = popen('date +\"%Y-%m-%d %H:%M\"', 'r');
    $rs = fread($fp, 1024);
    pclose($fp);
    $detection_time = trim($rs);

    return array(
        'cpu_usage'      => $cpu_usage,
        'mem_usage'      => $mem_usage,
        'hd_avail'       => $hd_avail,
        'hd_usage'       => $hd_usage,
        'task_running'   => $task_running,
        'detection_time' => $detection_time
    );
}
?>

調用示例

<?php
$stat = get_used_status();
printf('CPU: %.2f%%  Mem: %.2f%%  Disk: %sG free (%s%%)  Tasks: %d  Time: %s',
    $stat['cpu_usage'], $stat['mem_usage'], $stat['hd_avail'],
    $stat['hd_usage'], $stat['task_running'], $stat['detection_time']);
?>

關鍵點提醒

  • top -b -n 2 取第二次採樣更準確。
  • df -lh 只看根分區,若有多掛載點需調整 grep 模式。
  • 生產環境建議將指令路徑寫死(/usr/bin/top)並限制 PHP 執行權限。
  • 可擴充讀取 /proc/net/dev 獲取網卡流量、/proc/loadavg 獲取負載。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved