Linux平台系统状态检测与展示

Linux是一个文件系统,任何有关Linux系统运行的信息都会被包含到特定的文件里,这次我实现的是将cpu利用率与内存利用率和网速展示在前台,首先是读取相关文件信息插入到mysql数据库,再从数据库读取信息到前端

0-1 cpu利用率

在网上查询可知关于系统cpu和内存的信息在/proc/stat文件里,查看该文件

该文件包含了cpu活动的所有信息,第一行是cpu总的使用情况,所以我们只需要看第一行,第一行参数含义如下

user

从系统启动开始累计到当前时刻,处于用户态的运行时间,不包含 nice值为负进程
nice从系统启动开始累计到当前时刻,nice值为负的进程所占用的CPU时间
system从系统启动开始累计到当前时刻,处于核心态的运行时间
idle从系统启动开始累计到当前时刻,除IO等待时间以外的其它等待时间
iowait从系统启动开始累计到当前时刻,IO等待时间
irq从系统启动开始累计到当前时刻,硬中断时间
softirp从系统启动开始累计到当前时刻,软中断时间
stealstonwhich is the time spent in other operating systems when running in a virtualized environment
guest

which is the time spent running a virtual  CPU  for  guest operating systems under the control of the Linux kernel

 总的cpu时间计算方法为totalCpuTime = user + nice + system + idle + iowait + irq + softirq + stealstolen  +  guest

0-2 内存利用率

关于内存使用的信息在/proc/meminfo文件里,打开该文件,只需使用前两行数据即可算出每时刻内存的使用率

0-3 网速

同理找到网速相关的文件/proc/net/dev,打开

 关于参数含义

  • bytes: The total number of bytes of data transmitted or received by the interface.(接口发送或接收的数据的总字节数)
  • packets: The total number of packets of data transmitted or received by the interface.(接口发送或接收的数据包总数)
  • errs: The total number of transmit or receive errors detected by the device driver.(由设备驱动程序检测到的发送或接收错误的总数)
  • drop: The total number of packets dropped by the device driver.(设备驱动程序丢弃的数据包总数)
  • fifo: The number of FIFO buffer errors.(FIFO缓冲区错误的数量)
  • frame: The number of packet framing errors.(分组帧错误的数量)
  • colls: The number of collisions detected on the interface.(接口上检测到的冲突数)
  • compressed: The number of compressed packets transmitted or received by the device driver. (This appears to be unused in the 2.2.15 kernel.)(设备驱动程序发送或接收的压缩数据包数)
  • carrier: The number of carrier losses detected by the device driver.(由设备驱动程序检测到的载波损耗的数量)
  • multicast: The number of multicast frames transmitted or received by the device driver.(设备驱动程序发送或接收的多播帧数)

0-4具体实现

先是连接数据库

<?php
/**
 * Created by PhpStorm.
 * User: sydney
 * Date: 18-9-10
 * Time: 上午10:52
 */
header("CONTENT-TYPE:text/html;charset=UTF-8");
$mysql_server_name = "localhost";
$mysql_username = "root";
$mysql_password = "";
$mysql_database = "";
$mysql_table = "";

$mysqli = new mysqli($mysql_server_name, $mysql_username, $mysql_password);

if ($mysqli->connect_errno) {
    print("Connect failed: %s\n". $mysqli->connect_error);
    exit();
}

$mysqli->select_db($mysql_database);

在读取文件获取需要的信息,最后再用select从数据库读取数据以表格的形式输出

<?php
/**
 * Created by PhpStorm.
 * User: sydney
 * Date: 18-9-11
 * Time: 下午3:04
 */
//连接数据库
include "connect.php";
error_reporting(E_ERROR);
ini_set("display_errors","Off");


//计算cpu利用率
$openfile = fopen("/proc/stat","r") or die("unable to open file");
$string = fgets($openfile);
sleep(1);
$arr = explode(" ",$string);
$total1=$arr[1] +$arr[2]+$arr[3]+$arr[4]+$arr[5]+$arr[6]+$arr[7]+$arr[8];
$time1=$arr[1]+$arr[2]+$arr[3]+$arr[4]+$arr[6]+$arr[7]+$arr[8];
fclose($openfile);

sleep(1);
$openfile = fopen("/proc/stat","r") or die("unable to open file");
$string = fgets($openfile);
sleep(1);
$arr = explode(" ",$string);
$total2=$arr[1] +$arr[2]+$arr[3]+$arr[4]+$arr[5]+$arr[6]+$arr[7]+$arr[8];
$time2=$arr[1]+$arr[2]+$arr[3]+$arr[4]+$arr[6]+$arr[7]+$arr[8];
fclose($openfile);
$time=$time2-$time1;
$total=$total2-$total1;
$cpudata=round($time/$total,2);
$cpudatas=$cpudata*100;

//计算内存利用率
$str=shell_exec("more /proc/meminfo");
$mode="/(.+):\s*([0-9]+)/";
preg_match_all($mode,$str,$arr);
$mem=round($arr[2][1]/$arr[2][0],2);
$mem=1-$mem;
$mems=$mem*100;

//计算网速
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;
}
function merge_spaces ( $string )
{
    return preg_replace ( "/\s(?=\s)/","\\1", $string);
}
$file_path = "/proc/net/dev";
$openfile = fopen($file_path,"r");
$file_arr = file($file_path);
fclose($openfile);
$string = merge_spaces($file_arr[3]);
$data = explode(" ",$string);
$rec1 = $data[2];
$tra1 = $data[9];

sleep(1);
//计算网速
$net = hbw($tra1);
$time=date('y-m-d H:i:s');

$sql="insert into $mysql_table(cpudata, mem,rec,tra,net,dataline) values('$cpudatas','$mems','$rec1','$tra1','$net','$time')";
if ($mysqli->query($sql) === true) {
    print("存储成功");
} else {
    print("存储失败" . $mysqli->error);
}

$sql="select * from xitong ORDER BY dataline DESC";
$str=$mysqli->query($sql);
if($str && mysqli_num_rows($str)){
    while($row= mysqli_fetch_assoc($str)){
        $arr[]=$row;
    }
}
?>

<!DOCTYPE HTML>
<HTML>
<Head>
    <meta  http-equiv="CONTENT-TYPE" ; content="text/html"  ; charset="UTF-8">
    <title>系统检测</title>
    <style type="text/css">

    </style>
    <script type="text/javascript">
        $(function () {
            loadComments();
            $('#btnSend').click(function () {
                var post_data = $id+ $cpudata + $mem + $rec + $tra + $net + $dataline;//获取序列化表单元素
                //将请求提交到一般处理程序
                $.post("GetData.ashx", post_data, function (_datetext) {
                    if (_datetext == 1) {
                        alert("添加成功");
                        loadComments();
                    }
                })
            })
        })
        //页面加载事件
        function loadComments() {
            $.getJSON('GetData.ashx?id=' + Math.random(), null, function (_dataJSON) {
                //获取tbody标签
                var tbodyDate = $('#tbodyDate');
                tbodyDate.empty();
                //遍历JSON元素,添加到到Tbody
                for (var i = 0; i < _dataJSON.length; i++) {
                    tbodyDate.append
                    ($('<tr><td>' + _dataJSON[i].Id + '</td>' +
                        '<td>' + _dataJSON[i].cpudata + '</td>'+
                        '<td>'+_dataJSON[i].mem+'</td>'+
                        '<td>'+_dataJSON[i].rec+'</td></tr>'));
                }
            })
        }
    </script>
</Head>
<Body>
<div>
    <?php
    if(empty($data)){
        echo "当前没有数据";
    }
    else{
    foreach($arr as $value) {
        if($value['cpudata'] == NULL)
            continue;
    ?>
    <table width=500 border="0" align="center" cellpadding="5" cellspacing="1" bgcolor="#add3ef">
        <tr bgcolor="#eff3ff">
            <td>ID</td>
            <td><?php echo $value['id']; ?></td>
        </tr>
        <tr>
            <td>cpu利用率</td>
            <td><?php echo $value['cpudata']."%"; ?></td>
        </tr>
        <tr>
            <td>内存利用率</td>
            <td><?php echo $value['mem']."%"; ?></td>
        </tr>
        <tr>
            <td>rec</td>
            <td><?php echo $value['rec']; ?></td>
        </tr>
        <tr>
            <td>tra</td>
            <td><?php echo $value['tra']; ?></td>
        </tr>
        <tr>
            <td>net</td>
            <td><?php echo $value['net']; ?></td>
        </tr>
        <tr>
            <td>dataline</td>
            <td><?php echo $value['dataline']; ?></td>
        </tr>
    </table>
    ?>
</div>
<?php
}
}
?>
</Body>

</HTML>

 

最后效果

 

相关推荐
©️2020 CSDN 皮肤主题: 技术工厂 设计师:CSDN官方博客 返回首页