欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

分享一段php获取linux服务器状态的代码

程序员文章站 2023-12-02 08:38:58
简单的php获取linux服务器状态的代码,不多说-直接上函数: 复制代码 代码如下:function get_used_status(){  $fp = po...

简单的php获取linux服务器状态的代码,不多说-直接上函数:

复制代码 代码如下:

function get_used_status(){
  $fp = popen('top -b -n 2 | grep -e "^(cpu|mem|tasks)"',"r");//获取某一时刻系统cpu和内存使用情况
  $rs = "";
  while(!feof($fp)){
   $rs .= fread($fp,1024);
  }
  pclose($fp);
  $sys_info = explode("\n",$rs);

  $tast_info = explode(",",$sys_info[3]);//进程 数组
  $cpu_info = explode(",",$sys_info[4]);  //cpu占有量  数组
  $mem_info = explode(",",$sys_info[5]); //内存占有量 数组

  //正在运行的进程数
  $tast_running = trim(trim($tast_info[1],'running'));
  //cpu占有量
  $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);  //百分比
 

  /*硬盘使用率 begin*/
  $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'); //磁盘可用空间大小 单位g
  $hd_usage = trim($hd[4],'%'); //挂载点 百分比
  //print_r($hd);
  /*硬盘使用率 end*/ 

  //检测时间
  $fp = popen("date +\"%y-%m-%d %h:%m\"","r");
  $rs = fread($fp,1024);
  pclose($fp);
  $detection_time = trim($rs);

  /*获取ip地址  begin*/
  /*
  $fp = popen('ifconfig eth0 | grep -e "(inet addr)"','r');
  $rs = fread($fp,1024);
  pclose($fp);
  $rs = preg_replace("/\s{2,}/",' ',trim($rs));  //把多个空格换成 “_”
  $rs = explode(" ",$rs);
  $ip = trim($rs[1],'addr:');
  */
  /*获取ip地址 end*/
  /*
  $file_name = "/tmp/data.txt"; // 绝对路径: homedata.dat
  $file_pointer = fopen($file_name, "a+"); // "w"是一种模式,详见后面
  fwrite($file_pointer,$ip); // 先把文件剪切为0字节大小, 然后写入
  fclose($file_pointer); // 结束
  */

  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);
 }