php擷取linux伺服器狀態的代碼

來源:互聯網
上載者:User

例子,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. }

複製代碼
  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.