python3 运维监控脚本
时间: 2023-11-15 20:58:03 浏览: 52
下面是一个简单的 Python3 运维监控脚本示例,可以用于监控服务器的 CPU、内存、磁盘等指标:
```python
import psutil
def check_cpu_usage():
cpu_usage = psutil.cpu_percent(interval=1)
if cpu_usage > 80:
print("CPU usage is too high: %d%%" % cpu_usage)
def check_memory_usage():
virtual_memory = psutil.virtual_memory()
swap_memory = psutil.swap_memory()
if virtual_memory.percent > 80:
print("Virtual memory usage is too high: %d%%" % virtual_memory.percent)
if swap_memory.percent > 80:
print("Swap memory usage is too high: %d%%" % swap_memory.percent)
def check_disk_usage():
partitions = psutil.disk_partitions()
for partition in partitions:
usage = psutil.disk_usage(partition.mountpoint)
if usage.percent > 80:
print("Disk usage is too high: %d%%" % usage.percent)
if __name__ == '__main__':
check_cpu_usage()
check_memory_usage()
check_disk_usage()
```
这个示例使用了 Python 的 psutil 库来获取系统指标信息。其中,check_cpu_usage() 函数检查 CPU 使用率是否过高,check_memory_usage() 函数检查虚拟内存和交换内存使用率是否过高,check_disk_usage() 函数检查磁盘使用率是否过高。
你可以根据自己的需求添加或修改这些函数,例如加入网络流量、进程状态等检查。此外,你还可以使用定时任务工具(如 crontab 或 Windows 计划任务)来定时运行这个脚本,实现自动化监控。