用python编写centos7服务器巡检脚本!
import os
import sys
import subprocess
def check_cpu_usage():
cmd = "top -b -n1 | grep 'Cpu(s)' | awk '{print $2 + $4}'"
cpu_usage = subprocess.check_output(cmd, shell=True).decode().strip()
return float(cpu_usage)
def check_memory_usage():
cmd = "free -m | grep Mem | awk '{print $3/$2 * 100.0}'"
memory_usage = subprocess.check_output(cmd, shell=True).decode().strip()
return float(memory_usage)
def check_disk_usage():
cmd = "df -h | grep '/$' | awk '{print $5}'"
disk_usage = subprocess.check_output(cmd, shell=True).decode().strip()
return disk_usage
def check_network():
cmd = "ping -c 4 www.baidu.com"
try:
subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
return True
except subprocess.CalledProcessError:
return False
def main():
cpu_usage = check_cpu_usage()
memory_usage = check_memory_usage()
disk_usage = check_disk_usage()
network = check_network()
print("CPU使用率: {:.2f}%".format(cpu_usage))
print("内存使用率: {:.2f}%".format(memory_usage))
print("磁盘使用率: {}".format(disk_usage))
print("网络连通性: {}".format("正常" if network else "异常"))
if __name__ == "__main__":
main()