【功能点】获取linux服务器centos硬件的一些信息,获取cpu、内存、硬盘、网络带宽的使用率和单位转换


注意:以下代码都是放在服务器上访问,才会有结果的


/**
 * 获取CPU使用率
 */
function getCPURate($speed = 0.5)
{
    if (false === ($prevVal = @file("/proc/stat"))) {   //把整个文件读入到数组中
        return false;
    }

    $prevVal = implode($prevVal, PHP_EOL);
    $prevArr = explode(' ', trim($prevVal));
    $prevTotal = $prevArr[2] + $prevArr[3] + $prevArr[4] + $prevArr[5];
    $prevIdle = $prevArr[5];
    usleep($speed * 1000000);
    $val = @file("/proc/stat");
    $val = implode($val, PHP_EOL);
    $arr = explode(' ', trim($val));
    $total = $arr[2] + $arr[3] + $arr[4] + $arr[5];
    $idle = $arr[5];
    $intervalTotal = intval($total - $prevTotal);
    return round(100 * (($intervalTotal - ($idle - $prevIdle)) / $intervalTotal), 2);
}


/**
 * 获取全部速度
 * @return array|bool
 */
function getAllRate(){
    //打开进程文件指针。打开一个指向进程的管道,该进程由派生给定的 command 命令执行而产生
    $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*/

    /*网络使用率*/
    if (false === ($prevVal = @file("/proc/net/dev"))) {
        return false;
    }
    $result = file_get_contents("/proc/net/dev");

    preg_match("/lo:\s+\d+\s+\d+/", $result, $preg_str);
    $preg_str = str_replace("lo:",'',$preg_str);
    $preg_arr=explode(' ',$preg_str[0]);
    //var_dump($preg_arr,$result);die;
    $bytes = $preg_arr[1];
    $packets = $preg_arr[2];
    $net_usage  = round($packets*100/$bytes,2);

    $all=[
        'cpu_rate'=>$cpu_usage,
        'mem_rate'=>$mem_usage,
        'disk_rate'=>$hd_usage,
        'net_rate'=>$net_usage
    ];
   return $all;
}


/**
 * 获取内存使用率
 */
function getMemoryRate()
{

    if (false === ($str = @file("/proc/meminfo"))) return false;
    $str = implode("", $str);
    preg_match_all("/MemTotal\s{0,}\:+\s{0,}([\d\.]+).+?MemFree\s{0,}\:+\s{0,}([\d\.]+).+?Cached\s{0,}\:+\s{0,}([\d\.]+).+?SwapTotal\s{0,}\:+\s{0,}([\d\.]+).+?SwapFree\s{0,}\:+\s{0,}([\d\.]+)/s", $str, $buf);
    preg_match_all("/Buffers\s{0,}\:+\s{0,}([\d\.]+)/s", $str, $buffers);
    $res = array();
    $res['memTotal'] = round($buf[1][0] / 1024, 2);
    $res['memFree'] = round($buf[2][0] / 1024, 2);
    $res['memBuffers'] = round($buffers[1][0] / 1024, 2);
    $res['memCached'] = round($buf[3][0] / 1024, 2);
    $res['memUsed'] = $res['memTotal'] - $res['memFree'];
    $res['memPercent'] = (floatval($res['memTotal']) != 0) ? round($res['memUsed'] / $res['memTotal'] * 100, 2) : 0;

    $res['memRealUsed'] = $res['memTotal'] - $res['memFree'] - $res['memCached'] - $res['memBuffers']; //真实内存使用
   // $res['memRealUsed'] = $res['memTotal'] - $res['memFree'] ; //真实内存使用
    $res['memRealFree'] = $res['memTotal'] - $res['memRealUsed']; //真实空闲
    $res['memRealPercent'] = (floatval($res['memTotal']) != 0) ? round($res['memRealUsed'] / $res['memTotal'] * 100, 2) : 0; //真实内存使用率

    $res['memCachedPercent'] = (floatval($res['memCached']) != 0) ? round($res['memCached'] / $res['memTotal'] * 100, 2) : 0; //Cached内存使用率

    $res['swapTotal'] = round($buf[4][0] / 1024, 2);
    $res['swapFree'] = round($buf[5][0] / 1024, 2);
    $res['swapUsed'] = round($res['swapTotal'] - $res['swapFree'], 2);
    $res['swapPercent'] = (floatval($res['swapTotal']) != 0) ? round($res['swapUsed'] / $res['swapTotal'] * 100, 2) : 0;

    //判断内存如果小于1G,就显示M,否则显示G单位

    if ($res['memTotal'] < 1024) {
        $memTotal = $res['memTotal'] . " M";
        $mt = $res['memTotal'] . " M";
        $mu = $res['memUsed'] . " M";
        $mf = $res['memFree'] . " M";
        $mc = $res['memCached'] . " M"; //cache化内存
        $mb = $res['memBuffers'] . " M"; //缓冲
        $st = $res['swapTotal'] . " M";
        $su = $res['swapUsed'] . " M";
        $sf = $res['swapFree'] . " M";
        $swapPercent = $res['swapPercent'];
        $memRealUsed = $res['memRealUsed'] . " M"; //真实内存使用
        $memRealFree = $res['memRealFree'] . " M"; //真实内存空闲
        $memRealPercent = $res['memRealPercent']; //真实内存使用比率
        $memPercent = $res['memPercent']; //内存总使用率
        $memCachedPercent = $res['memCachedPercent']; //cache内存使用率
    } else {
        $memTotal = round($res['memTotal'] / 1024, 3) . " G";
        $mt = round($res['memTotal'] / 1024, 3) . " G";
        $mu = round($res['memUsed'] / 1024, 3) . " G";
        // $mf = round($res['memFree'] / 1024, 3) . " G";
        $mc = round($res['memCached'] / 1024, 3) . " G";
        $mb = round($res['memBuffers'] / 1024, 3) . " G";
        $st = round($res['swapTotal'] / 1024, 3) . " G";
        $su = round($res['swapUsed'] / 1024, 3) . " G";
        $sf = round($res['swapFree'] / 1024, 3) . " G";
        $swapPercent = $res['swapPercent'];
        $memRealUsed = round($res['memRealUsed'] / 1024, 3) . " G"; //真实内存使用
        $memRealFree = round($res['memRealFree'] / 1024, 3) . " G"; //真实内存空闲
        $memRealPercent = $res['memRealPercent']; //真实内存使用比率
        $memPercent = $res['memPercent']; //内存总使用率
        $memCachedPercent = $res['memCachedPercent']; //cache内存使用率
    }

    $res['u_memTotal'] = $memTotal;
    $res['u_memTotal'] = $mt;
    $res['u_memUsed'] = $mu;
    // $res['u_memFree'] = $mf;
    $res['u_memCached'] = $mc; //cache化内存
    $res['u_memBuffers'] = $mb; //缓冲
    $res['u_swapTotal'] = $st;
    $res['u_swapUsed'] = $su;
    $res['u_swapFree'] = $sf;
    $res['u_swapPercent'] = $swapPercent;
    $res['u_memRealUsed'] = $memRealUsed; //真实内存使用
    $res['u_memRealFree'] = $memRealFree; //真实内存空闲
    $res['u_memRealPercent'] = $memRealPercent; //真实内存使用比率
    $res['u_memPercent'] = $memPercent; //内存总使用率
    $res['u_memCachedPercent'] = $memCachedPercent; //cache内存使用率
    return $res['u_memRealPercent'];
}


/**
 * 硬盘使用率
 */

function getDiskRate()
{
    $fp = popen('df -lh | grep -E "^(/)"',"r"); //读。返回的是文件指针
    $rs = fread($fp,1024);                                //最多读取1024字节
    pclose($fp);                                                 //关闭
    $rs = preg_replace("/\s{2,}/",' ',$rs);  //把读出来的空格(至少匹配2次空白符)替换成 “_”
    $hd = explode(" ",$rs);                             //拿空格分割
    $hd_avail = !strrpos($hd[1],"T")?trim($hd[1],'G'):trim($hd[1],'T')*1024;    //磁盘大小,/dev/sda1
    $hd_avail2 = !strrpos($hd[6],"T")?trim($hd[6],'G'):trim($hd[6],'T')*1024;   //磁盘大小,/dev/sda3
    $hd_usage = !strrpos($hd[2],"T")?trim($hd[2],'G'):trim($hd[2],'T')*1024;    //磁盘可用空间大小 单位G
    $hd_usage2 = !strrpos($hd[7],"T")?trim($hd[7],'G'):trim($hd[7],'T')*1024;
    //echo $hd_avail."/".$hd_avail2."/".$hd_usage."/".$hd_usage2;
    $bili = ($hd_usage+$hd_usage2)/($hd_avail+$hd_avail2);
    $iPercent = round($bili*100,2);                 //2位小数
    return $iPercent;
}


/**
 * 获取网络带宽使用率
 * @return bool
 */
function getNetRate(){
    if (false === ($prevVal = @file("/proc/net/dev"))) {
        return false;
    }

    $result = file_get_contents("/proc/net/dev");
    exec("/sbin/ifconfig |grep eth",$res);
    $recive=$trancate=$speed=0;
    foreach($res as $v){
        $data=$mbs='';
        $eth =explode(' ',$v)[0];
        // var_dump($eth);
        //echo "/sbin/ifconfig $eth |grep RUNNING";
        exec("/sbin/ifconfig $eth |grep RUNNING",$data);
        if(!empty($data)){ //网口是开启的
            preg_match("/$eth:\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+/", $result, $preg_str);
            //var_dump($preg_str);die;
            $preg_str = str_replace("$eth: ",'',$preg_str);
            $preg_arr=explode(' ',$preg_str[0]);
            $recive += $preg_arr[0];
            $trancate += $preg_arr[35];

            exec("/sbin/ethtool $eth",$ms);
            if(strpos($ms[12],'100Mb/s')!=false){
                $speed += 100;
            }
            if(strpos($ms[12],'1000Mb/s')!=false){
                $speed += 1000;
            }

        }
    }

    //$rate = round($packets*$speed/$bytes,2);
    // var_dump($rate);die;
    return $rate;



}


/**
 * 单位转换
 * @param $size
 * @return int|string
 */
function hbw($size) {
    $size *= 8;
    if($size > 1024 * 1024 * 1024) {
        $size = round($size / 1073741824 * 100) / 100 . ' Gbps';
    } elseif($size > 1024 * 1024) {
        $size = round($size / 1048576 * 100) / 100 . ' Mbps';
    } elseif($size > 1024) {
        $size = round($size / 1024 * 100) / 100 . ' Kbps';
    } else {
        $size = $size . ' Bbps';
    }
    return $size;
}

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33862644/article/details/80316735
个人分类: php
上一篇【功能点】php导出html和下载文件的耗时算法
下一篇PHP 开发者该知道的 5 个 Composer 小技巧
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭