首页  >  文章  >  后端开发  >  php获取linux服务器状态的代码

php获取linux服务器状态的代码

WBOY
WBOY原创
2016-07-25 09:11:591004浏览

例子,php获取linux服务器状态的代码。

  1. function get_used_status(){

  2. $fp = popen('top -b -n 2 | grep -E "^(Cpu|Mem|Tasks)"',"r");//获取某一时刻系统cpu和内存使用情况
  3. $rs = "";
  4. while(!feof($fp)){
  5. $rs .= fread($fp,1024);
  6. }
  7. pclose($fp);
  8. $sys_info = explode("\n",$rs);
  9. $tast_info = explode(",",$sys_info[3]);//进程 数组
  10. $cpu_info = explode(",",$sys_info[4]); //CPU占有量 数组
  11. $mem_info = explode(",",$sys_info[5]); //内存占有量 数组
  12. //正在运行的进程数
  13. $tast_running = trim(trim($tast_info[1],'running'));
  14. //CPU占有量
  15. $cpu_usage = trim(trim($cpu_info[0],'Cpu(s): '),'%us'); //百分比
  16. //内存占有量

  17. $mem_total = trim(trim($mem_info[0],'Mem: '),'k total');
  18. $mem_used = trim($mem_info[1],'k used');
  19. $mem_usage = round(100*intval($mem_used)/intval($mem_total),2); //百分比
  20. /*硬盘使用率 begin*/
  21. $fp = popen('df -lh | grep -E "^(/)"',"r");
  22. $rs = fread($fp,1024);
  23. pclose($fp);
  24. $rs = preg_replace("/\s{2,}/",' ',$rs); //把多个空格换成 “_”
  25. $hd = explode(" ",$rs);
  26. $hd_avail = trim($hd[3],'G'); //磁盘可用空间大小 单位G
  27. $hd_usage = trim($hd[4],'%'); //挂载点 百分比
  28. //print_r($hd);
  29. /*硬盘使用率 end*/
  30. //检测时间

  31. $fp = popen("date +\"%Y-%m-%d %H:%M\"","r");
  32. $rs = fread($fp,1024);
  33. pclose($fp);
  34. $detection_time = trim($rs);
  35. /*获取IP地址 begin*/

  36. /*
  37. $fp = popen('ifconfig eth0 | grep -E "(inet addr)"','r');
  38. $rs = fread($fp,1024);
  39. pclose($fp);
  40. $rs = preg_replace("/\s{2,}/",' ',trim($rs)); //把多个空格换成 “_”
  41. $rs = explode(" ",$rs);
  42. $ip = trim($rs[1],'addr:');
  43. */
  44. /*获取IP地址 end*/
  45. /*
  46. $file_name = "/tmp/data.txt"; // 绝对路径: homedata.dat
  47. $file_pointer = fopen($file_name, "a+"); // "w"是一种模式,详见后面
  48. fwrite($file_pointer,$ip); // 先把文件剪切为0字节大小, 然后写入
  49. fclose($file_pointer); // 结束
  50. */
  51. return array('cpu_usage'=>$cpu_usage,'mem_usage'=>$mem_usage,'hd_avail'=>$hd_avail,'hd_usage'=>$hd_usage,'tast_running'=>$tast_running,'detection_time'=>$detection_time);

  52. }
复制代码


声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn