🗣 Wd提问: php 监控服务器
🤖 Ai回答: 在 PHP 中监控服务器,通常指的是通过编写脚本或使用框架来实时获取服务器的运行状态(如 CPU、内存、磁盘、网络、进程等),并进行日志记录、报警或可视化展示。以下是几种常见的方法和实现思路:
🔍 一、常用的服务器监控指标
| 指标 | 说明 |
| CPU 使用率 | 系统负载、用户/系统占用比 |
| 内存使用情况 | 总内存、已用、空闲、缓存 |
| 磁盘空间 | 根目录、指定目录剩余空间 |
| 网络流量 | 上行/下行带宽使用 |
| 进程数量 | 当前运行的进程数 |
| 服务状态 | 如 Apache/Nginx/MySQL 是否运行 |
🛠️ 二、实现方式(基于 PHP)
✅ 1、使用 `shell_exec()` 调用系统命令
最简单的方式是调用 Linux 命令,再解析输出。
示例:获取内存使用情况
php
<?php
function getMemoryUsage() {
$output = shell_exec('free -m');
$lines = explode(\n, $output);
$memLine = explode( , $lines[1]);
// 去除空值
$memLine = array_filter($memLine);
$memLine = array_values($memLine);
$total = $memLine[1]; // 总内存 (MB)
$used = $memLine[2]; // 已用内存 (MB)
$free = $memLine[3]; // 空闲内存 (MB)
return [
'total' = $total,
'used' = $used,
'free' = $free,
'usage_percent' = round(($used / $total) * 100, 2)
];
}
print_r(getMemoryUsage());
示例:获取磁盘使用情况
php
<?php
function getDiskUsage($path = '/') {
$total = disk_total_space($path);
$free = disk_free_space($path);
$used = $total $free;
$percent = round(($used / $total) * 100, 2);
return [
'path' = $path,
'total' = round($total / (1024*1024*1024), 2), // GB
'used' = round($used / (1024*1024*1024), 2),
'free' = round($free / (1024*1024*1024), 2),
'percent' = $percent
];
}
print_r(getDiskUsage('/'));
示例:获取 CPU 使用率(近似)
php
<?php
function getCpuUsage() {
$output = shell_exec('top -bn1 | grep Cpu(s) | awk {print \$2}');
$cpuUsage = trim($output);
return floatval($cpuUsage);
}
echo CPU Usage: 、getCpuUsage() 、%;
⚠️ 说明:`top -bn1` 是非交互式模式,只取一次数据,适合定时任务。
✅ 2、获取系统负载(Load Average)
php
<?php
function getLoadAverage() {
if (file_exists('/proc/loadavg')) {
$load = file_get_contents('/proc/loadavg');
$parts = explode(' ', trim($load));
return [
'1min' = floatval($parts[0]),
'5min' = floatval($parts[1]),
'15min' = floatval($parts[2])
];
}
return null;
}
print_r(getLoadAverage());
✅ 3、检查服务是否运行(如 MySQL、Apache)
php
<?php
function isServiceRunning($service) {
$result = shell_exec(systemctl is-active $service 2/dev/null);
return trim($result) === 'active';
}
echo isServiceRunning('mysql') ? 'MySQL Running' : 'MySQL Not Running';
echo \n;
echo isServiceRunning('apache2') ? 'Apache Running' : 'Apache Not Running';
✅ 4、记录日志 & 发送告警(可选)
php
<?php
function logAlert($message) {
$logFile = '/var/log/server-monitor.log';
$timestamp = date('Y-m-d H:i:s');
file_put_contents($logFile, [$timestamp] ALERT: $message\n, FILE_APPEND);
}
// 举例:磁盘使用超过 90% 就发警告
$disk = getDiskUsage('/');
if ($disk['percent'] 90) {
logAlert(Disk usage is high: {$disk['percent']}%);
}
📊 三、进阶方案(推荐用于生产环境)
1、Prometheus + Node Exporter + PHP Pushgateway
安装 [Node Exporter](https://github.com/prometheus/node_exporter) 到服务器。
在 PHP 中使用 `pushgateway` 推送指标。
php
<?php
// push_metrics.php
require_once 'vendor/autoload.php';
use GuzzleHttp\Client;
$client = new Client();
$data = [
'cpu_usage' = getCpuUsage(),
'memory_usage_percent' = getMemoryUsage()['usage_percent'],
'disk_usage_percent' = getDiskUsage()['percent']
];
try {
$client-post('http://localhost:9091/metrics/job/php_server', [
'form_params' = $data
]);
} catch (Exception $e) {
error_log(Push failed: 、$e-getMessage());
}
然后用 Prometheus 抓取数据,配合 Grafana 可视化。
2、使用 Laravel + Scheduler + 队列
bash
定时任务(crontab)
* * * * * cd /path-to-project && php artisan schedule:run /dev/null 2&1
php
// app/Console/Commands/MonitorServer.php
class MonitorServer extends Command
{
protected $signature = 'server:monitor';
protected $description = 'Monitor server health';
public function handle()
{
$memory = getMemoryUsage();
$disk = getDiskUsage('/');
$load = getLoadAverage();
$this-info(Memory: {$memory['usage_percent']}%);
$this-info(Disk: {$disk['percent']}%);
$this-info(Load: {$load['1min']});
if ($disk['percent'] 90) {
Notification::send(new ServerAlert(Disk full: {$disk['percent']}%));
}
}
}
📌 四、注意事项与安全建议
| 注意事项 | 建议 |
| 避免直接暴露监控脚本 | 用 Nginx/Apache 限制访问,加 Token |
| 使用 `escapeshellarg()` 防止注入 | 如 `shell_exec(df -h $path)` |
| 不要频繁执行系统命令 | 建议每 1~5 分钟执行一次 |
| 日志写入权限 | 确保 PHP 有写入日志文件的权限 |
| 使用守护进程(如 Supervisor) | 监控脚本可长期运行 |
📦 五、推荐工具包
[PHP-Metrics](https://github.com/phpmetrics/PhpMetrics) – 代码质量分析(不是服务器)
[Symfony Process Component](https://symfony.com/doc/current/components/process.html) – 安全执行系统命令
[Grafana + Prometheus + Node Exporter] – 最佳实践组合
✅ 总结
| 方法 | 适用场景 | 优点 | 缺点 |
| `shell_exec()` + 命令 | 快速原型 | 简单直接 | 安全性差 |
| Laravel + Scheduler | Web 项目集成 | 易维护 | 依赖框架 |
| Prometheus + PushGateway | 大型系统 | 可视化、告警强 | 配置复杂 |
如果你希望我帮你写一个完整的 服务器监控脚本(支持日志、邮件报警、定时执行),可以告诉我你的需求,比如:
你用什么系统?(Linux / CentOS / Ubuntu)
是否有数据库?
是否需要邮件/钉钉/企业微信通知?
是否需要网页展示?
我可以为你生成完整可运行的代码 👇
📣 商家广告:





0
IP地址: 131.145.80.221
搜索次数: 21
提问时间: 2025-11-15 11:15:33
🛒 域名购买:
chuisou.com.cn
uj.gs
396.net.cn
op.gs
zhansou.cn
8333.top
z.gz.cn
ltqz.cn
fygz.cn
vj.gs
❓️ 热门提问:
风机房吸音墙
域名安全交易
idc行业数据
服务器分割vps
新开服务器手游
平面设计分享网站
域名买卖平台排名
php连接mysql 大数据
adult域名
2025磁力搜索引擎
豌豆Ai站群搜索引擎系统
🌐 域名评估:
aaaa.cab
nn.jl.cn
musk.ski
yu7.js.cn
wh.gg
miannian.cn
guzun.cn
ag.cq.cn
nxak.cn
vtol.autos
⛏ 最新挖掘:
凯里酸汤鱼
贵阳烤脑花
都匀毛尖茶
花溪牛肉粉
贵阳烤生蚝
贵阳烤豆腐
贵阳纸包鱼
贵阳特色菜
🖌 热门作画:
🤝 关于我们:
豌豆Ai
域名
建站
站群
留痕
推广
评估
源码
开发Ai
工具
日记
价格
加盟
广告
流量
留言
联系
🗨 加入群聊:
🔗 友情链接:
검색 엔진 개발
广州月饼厂家
ai提问
🧰 站长工具:
Ai工具 whois查询 搜索
📢 温馨提示:本站所有问答由Ai自动创作,内容仅供参考,若有误差请用“联系”里面信息通知我们人工修改或删除。
👉 技术支持:本站由豌豆Ai提供技术支持,使用的最新版:《豌豆Ai站群搜索引擎系统 V.25.10.25》搭建本站。