[开发笔记]Linux PHP获取CPU内存带宽使用情况

By | 2016 年 5 月 4 日
<?php
/* CPU */
unset($pattern, $str, $out);
$str = shell_exec('more /proc/stat');
$pattern = "/(cpu[0-9]?)[\s]+([0-9]+)[\s]+([0-9]+)[\s]+([0-9]+)[\s]+([0-9]+)[\s]+([0-9]+)[\s]+([0-9]+)[\s]+([0-9]+)/";
preg_match_all($pattern, $str, $out);
$res['cpu'] = round(100*($out[1][0]+$out[2][0]+$out[3][0])/($out[4][0]+$out[5][0]+$out[6][0]+$out[7][0]),2);

/* MEM */
unset($pattern, $str, $out);
$str = shell_exec('more /proc/meminfo');
$pattern = "/(.+):\s*([0-9]+)/";
preg_match_all($pattern, $str, $out);
$res['mem']['total'] = round($out[2][0]/1024);
$res['mem']['use'] = round(($out[2][0]-$out[2][1]-$out[2][2]-$out[2][3])/1024);
$res['mem']['percent'] = round(100*($out[2][0]-$out[2][1]-$out[2][2]-$out[2][3])/$out[2][0]);

/* NET */
unset($pattern, $str, $out);
$str = shell_exec('cat /proc/net/dev');
$pattern = "/eth.*/";
preg_match_all($pattern, $str, $out);
foreach ($out[0] as &$value) {
  $eth = explode(":",$value);
  $net[$eth[0]] = array_values(array_filter(explode(' ',$eth[1]),"check"));
}
function check($var){
  if(is_numeric($var)){
    return true;
  }else{
    return false;
  }
}

foreach ($net as $key => $value) {
 	$res['net'][$key]['in'] = $value[0];
 	$res['net'][$key]['out'] = $value[8];
}
print_r($res);

发表评论

电子邮件地址不会被公开。 必填项已用*标注