Python 巡检脚本

简介

Python 巡检脚本是一种用于检查系统状态、配置和运行情况的脚本工具。它可以自动化执行诸如检查网络连接、磁盘空间、CPU 使用率、内存使用率等任务,从而提高系统维护和监控的效率。

本文将介绍如何编写一个简单的 Python 巡检脚本,并使用一些常用的模块和技术来实现巡检功能。

巡检脚本示例

以下是一个简单的巡检脚本示例,用于检查系统的磁盘空间使用率:

import os

def check_disk_space(path):
    total, used, free = os.statvfs(path)[:3]
    disk_space = {
        'total': total * 4 / 1024 / 1024,  # in GB
        'used': used * 4 / 1024 / 1024,  # in GB
        'free': free * 4 / 1024 / 1024,  # in GB
        'usage': used / total * 100  # in percentage
    }
    return disk_space

if __name__ == '__main__':
    path = '/'
    disk_space = check_disk_space(path)
    print(f"Total disk space: {disk_space['total']} GB")
    print(f"Used disk space: {disk_space['used']} GB")
    print(f"Free disk space: {disk_space['free']} GB")
    print(f"Disk space usage: {disk_space['usage']}%")

在以上示例中,我们使用了 os 模块来获取指定路径的磁盘空间信息。os.statvfs(path) 返回一个元组,包含了文件系统的统计信息,我们通过取出元组的前三个元素来获取总空间、已用空间和可用空间的字节数。然后,我们将这些字节数转换为以 GB 为单位的值,并计算磁盘空间使用率。

巡检示例结果

我们可以运行以上脚本来获取系统的磁盘空间使用情况。下面是一些示例结果:

Total disk space: 190.24609375 GB
Used disk space: 122.0888671875 GB
Free disk space: 68.1572265625 GB
Disk space usage: 64.15%

巡检脚本的应用

除了磁盘空间使用率的巡检,我们还可以扩展巡检脚本来检查其他系统状态和配置。以下是一些可以添加到巡检脚本中的功能:

1. 网络连接检查

import socket

def check_network_connection(host, port):
    try:
        socket.create_connection((host, port), timeout=5)
        return True
    except OSError:
        return False

if __name__ == '__main__':
    host = 'www.example.com'
    port = 80
    if check_network_connection(host, port):
        print(f"Connected to {host}:{port}")
    else:
        print(f"Cannot connect to {host}:{port}")

以上示例中,我们使用 socket.create_connection() 函数来尝试建立与指定主机和端口的连接。如果连接成功,返回 True;否则返回 False。

2. CPU 和内存使用率检查

import psutil

def check_cpu_usage():
    return psutil.cpu_percent(interval=1)

def check_memory_usage():
    return psutil.virtual_memory().percent

if __name__ == '__main__':
    cpu_usage = check_cpu_usage()
    memory_usage = check_memory_usage()
    print(f"CPU usage: {cpu_usage}%")
    print(f"Memory usage: {memory_usage}%")

以上示例中,我们使用了 psutil 模块来获取 CPU 和内存的使用率。psutil.cpu_percent(interval=1) 返回一个整数,表示当前系统的 CPU 使用率。psutil.virtual_memory().percent 返回一个浮点数,表示当前系统的内存使用率。

巡检结果可视化

为了更直观地呈现巡检结果,我们可以使用 matplotlib 模块来绘制饼状图。下面是一个示例,展示了磁盘空间使用率的饼状图:

import matplotlib.pyplot as plt

def plot_disk_space_usage(disk_space):
    labels = ['Used', 'Free']
    sizes = [