在CentOS系统中,你可以使用Python编写脚本来进行系统监控。以下是一些基本步骤和示例,帮助你开始使用Python进行系统监控:
首先,确保你已经安装了Python。CentOS 7默认安装了Python 2.7,但推荐使用Python 3。你可以使用以下命令安装Python 3和pip:
sudo yum install python3 python3-pip
然后,安装一些常用的系统监控库,例如psutil
和matplotlib
:
pip3 install psutil matplotlib
下面是一个简单的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()
将上述脚本保存为monitor.py
,然后在终端中运行:
python3 monitor.py
你可以使用cron
来定期运行监控脚本。编辑crontab
文件:
crontab -e
添加以下行以每分钟运行一次监控脚本:
* * * * * /usr/bin/python3 /path/to/monitor.py >> /var/log/monitor.log 2>&1
保存并退出编辑器。
你可以根据需要扩展监控脚本,例如:
通过这些步骤,你可以在CentOS系统上使用Python进行基本的系统监控。