« 第一个iPhone应用诞生啦 奇矩互动招聘进行中 »

PHP监控linux服务器负载

前面我们说到《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");
    return 0;
}

编译该文件gcc -o ipt -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就可以上述这种方法来做。

“PHP监控linux服务器负载”

3条回复
  1. 按照上面的实例,我们可以用PHP来做任何我们想执行的Linux系统命令,谢谢

  2. 使用visudo将需要执行的命令和用户对应起来,也可以

  3. chmod u+s ./w 这个应该是设置suid位吧?

回复留言

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-Spam Image

你可以使用XHTML标签: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>