Share a piece of php code to get linux server status

  • 2021-06-28 11:50:25
  • OfStack

Simple php gets code for linux server state, not to mention - directly up the function:


function get_used_status(){
  $fp = popen('top -b -n 2 | grep -E "^(Cpu|Mem|Tasks)"',"r");// Get something 1 Time System cpu And memory usage 
  $rs = "";
  while(!feof($fp)){
   $rs .= fread($fp,1024);
  }
  pclose($fp);
  $sys_info = explode("\n",$rs);
  $tast_info = explode(",",$sys_info[3]);// process   array 
  $cpu_info = explode(",",$sys_info[4]);  //CPU Occupancy    array 
  $mem_info = explode(",",$sys_info[5]); // Memory occupancy   array 
  // Number of running processes 
  $tast_running = trim(trim($tast_info[1],'running'));
  //CPU Occupancy 
  $cpu_usage = trim(trim($cpu_info[0],'Cpu(s): '),'%us');  // Percentage 

  // Memory occupancy 
  $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);  // Percentage 
  
  /* Hard Disk Usage  begin*/
  $fp = popen('df -lh | grep -E "^(/)"',"r");
  $rs = fread($fp,1024);
  pclose($fp);
  $rs = preg_replace("/\s{2,}/",' ',$rs);  // Replace multiple spaces with   " _ " 
  $hd = explode(" ",$rs);
  $hd_avail = trim($hd[3],'G'); // Disk free space size   Company G
  $hd_usage = trim($hd[4],'%'); // mount point   Percentage 
  //print_r($hd);
  /* Hard Disk Usage  end*/  

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

  /* Obtain IP address   begin*/
  /*
  $fp = popen('ifconfig eth0 | grep -E "(inet addr)"','r');
  $rs = fread($fp,1024);
  pclose($fp);
  $rs = preg_replace("/\s{2,}/",' ',trim($rs));  // Replace multiple spaces with   " _ " 
  $rs = explode(" ",$rs);
  $ip = trim($rs[1],'addr:');
  */
  /* Obtain IP address  end*/
  /*
  $file_name = "/tmp/data.txt"; //  Absolute path : homedata.dat 
  $file_pointer = fopen($file_name, "a+"); // "w" yes 1 Various modes, detailed below 
  fwrite($file_pointer,$ip); //  Cut the file first to 0 Byte size,   Then write 
  fclose($file_pointer); //  End 
  */

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


Related articles: