centos

CentOS如何利用Python进行系统监控

小樊
95
2025-02-14 12:06:24
栏目: 编程语言

在CentOS系统中,你可以使用Python编写脚本来进行系统监控。以下是一些基本步骤和示例,帮助你开始使用Python进行系统监控:

1. 安装必要的Python库

首先,确保你已经安装了Python。CentOS 7默认安装了Python 2.7,但推荐使用Python 3。你可以使用以下命令安装Python 3和pip:

sudo yum install python3 python3-pip

然后,安装一些常用的系统监控库,例如psutilmatplotlib

pip3 install psutil matplotlib

2. 编写监控脚本

下面是一个简单的Python脚本示例,用于监控CPU使用率、内存使用率和磁盘I/O。

import psutil
import time
import matplotlib.pyplot as plt

# 初始化数据列表
cpu_usage = []
memory_usage = []
disk_io = []

# 监控间隔(秒)
interval = 5

# 监控时长(秒)
duration = 60

# 开始监控
end_time = time.time() + duration
while time.time() < end_time:
    # 获取CPU使用率
    cpu_usage.append(psutil.cpu_percent(interval=interval))
    
    # 获取内存使用率
    memory = psutil.virtual_memory()
    memory_usage.append(memory.percent)
    
    # 获取磁盘I/O统计信息
    disk_io_stats = psutil.disk_io_counters()
    disk_io.append(disk_io_stats.read_bytes + disk_io_stats.write_bytes)
    
    # 打印当前监控数据
    print(f"Time: {time.strftime('%H:%M:%S')}, CPU Usage: {cpu_usage[-1]}%, Memory Usage: {memory_usage[-1]}%, Disk I/O: {disk_io[-1]} bytes")
    
    # 等待下一个监控间隔
    time.sleep(interval)

# 绘制图表
plt.figure(figsize=(12, 6))

plt.subplot(3, 1, 1)
plt.plot(cpu_usage, label='CPU Usage (%)')
plt.xlabel('Time')
plt.ylabel('Usage (%)')
plt.title('CPU Usage Over Time')
plt.legend()

plt.subplot(3, 1, 2)
plt.plot(memory_usage, label='Memory Usage (%)', color='orange')
plt.xlabel('Time')
plt.ylabel('Usage (%)')
plt.title('Memory Usage Over Time')
plt.legend()

plt.subplot(3, 1, 3)
plt.plot(disk_io, label='Disk I/O (bytes)', color='green')
plt.xlabel('Time')
plt.ylabel('I/O (bytes)')
plt.title('Disk I/O Over Time')
plt.legend()

plt.tight_layout()
plt.show()

3. 运行监控脚本

将上述脚本保存为monitor.py,然后在终端中运行:

python3 monitor.py

4. 定期运行监控脚本

你可以使用cron来定期运行监控脚本。编辑crontab文件:

crontab -e

添加以下行以每分钟运行一次监控脚本:

* * * * * /usr/bin/python3 /path/to/monitor.py >> /var/log/monitor.log 2>&1

保存并退出编辑器。

5. 进一步扩展

你可以根据需要扩展监控脚本,例如:

通过这些步骤,你可以在CentOS系统上使用Python进行基本的系统监控。

0
看了该问题的人还看了