PHP監控linux伺服器負載

來源:互聯網
上載者:User

前面我們說到《PHP執行linux系統命令》:http://www.ccvita.com/390.html,即是為本文做鋪墊。在實際項目的應用中,我們由於各種條件的現實,利用PHP來實現伺服器負載監控將是一種更為靈活的方式。

由於Web Server以及PHP的實現方式所限,我們在現實環境中很難利用PHP去調用一些Linux中需要root許可權才能執行的程式,對此,我從網上找到另外一種方式來繞開這個限制。首先先寫個c程式中轉調用系統命令,然後用PHP去執行此c程式。

c程式
首先寫個c檔案,比如/usr/local/ismole/w.c

//note 由於wordpress編輯器的原因,請將此代碼中標頭檔多餘的空格去除
#include< stdio.h>
#include< stdlib.h>
#include< systypes.h>
#include< unistd.h>
 
int main()
{
    uid_t uid ,euid;
 
    //note 獲得當前的uid
    uid = getuid();
    //note 獲得當前euid
    euid = geteuid();
 
    //note 交換這兩個id
    if(setreuid(euid, uid))
        perror("setreuid");
 
    //note 執行將要執行linux系統命令
    system("/usr/bin/w");
    return0;
}


編譯該檔案gcc -o w -Wall w.c,這時會在目前的目錄下產生程式w。
改變此程式的屬主chmod u+s ./w。

 

 

PHP執行
檔案內容如下,放在web目錄下,訪問就會輸出當前的伺服器負載情況。

< ?php
/*
        More & Original PHP Framwork
        Copyright (c) 2007 - 2008 IsMole Inc.
 
        $Id: serverMonitor.php 408 2008-12-02 08:07:40Z kimi $
*/
 
//note key的驗證過程
if($key != $authkey) {
//        exit('key error);
}
 
$last_line = exec('/usr/local/ismole/w', $retval);
 
$returnArray = explode("load average: ", $retval[0]);
$returnString = $returnArray[1];
 
echo $returnString;

按照上面的執行個體,我們可以用PHP來做任何我們想執行的Linux系統命令,SVN更新,伺服器監控,備份,恢複,日常維護等等。比如《利用SVN搭建測試伺服器》:http://www.ccvita.com/383.html就可以上述這種方法來做。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.