You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
python/MD/Python 自动化运维案例.md

8.3 KiB

Python 自动化运维案例

作者:行癫(盗版必究)


一:获取监控系统信息

1.运行环境

python 3

pip 3

2.脚本文件

#!/usr/bin/env python3
import psutil
import socket
import datetime

def get_cpu_info():
    return {
        "cpu_percent": psutil.cpu_percent(interval=1),
        "cpu_cores": psutil.cpu_count(logical=False),
        "cpu_threads": psutil.cpu_count(logical=True)
    }

def get_memory_info():
    mem = psutil.virtual_memory()
    return {
        "total": mem.total,
        "available": mem.available,
        "used": mem.used,
        "percent": mem.percent
    }

def get_disk_info():
    partitions = psutil.disk_partitions()
    disk_info = {}
    for p in partitions:
        usage = psutil.disk_usage(p.mountpoint)
        disk_info[p.mountpoint] = {
            "total": usage.total,
            "used": usage.used,
            "free": usage.free,
            "percent": usage.percent
        }
    return disk_info

def get_network_info():
    net_io = psutil.net_io_counters()
    return {
        "bytes_sent": net_io.bytes_sent,
        "bytes_recv": net_io.bytes_recv
    }

def get_uptime():
    boot_time = datetime.datetime.fromtimestamp(psutil.boot_time())
    now = datetime.datetime.now()
    return str(now - boot_time).split('.')[0]

def get_hostname():
    return socket.gethostname()

def main():
    print(f"主机名: {get_hostname()}")
    print(f"系统运行时间: {get_uptime()}")
    print("\n=== CPU 信息 ===")
    for k, v in get_cpu_info().items():
        print(f"{k}: {v}")

    print("\n=== 内存 信息 ===")
    for k, v in get_memory_info().items():
        print(f"{k}: {v // (1024 * 1024)} MB")

    print("\n=== 磁盘 信息 ===")
    disk_info = get_disk_info()
    for mount, info in disk_info.items():
        print(f"\n挂载点: {mount}")
        for k, v in info.items():
            if isinstance(v, (int, float)):
                print(f"  {k}: {v // (1024 * 1024)} MB" if 'percent' not in k else f"  {k}: {v}%")
            else:
                print(f"  {k}: {v}")

    print("\n=== 网络 信息 ===")
    net_info = get_network_info()
    print(f"已发送: {net_info['bytes_sent'] // (1024 * 1024)} MB")
    print(f"已接收: {net_info['bytes_recv'] // (1024 * 1024)} MB")

if __name__ == "__main__":
    main()

3.参数解释

  • psutil: Python 的系统和进程工具库,用于获取 CPU、内存、磁盘、网络等信息。
  • socket: 标准库模块,用于获取网络信息,如主机名。
  • datetime: 标准库模块,用于处理日期和时间,例如计算开机时长。

🧠 获取 CPU 信息

def get_cpu_info():

定义一个函数 get_cpu_info,用来收集 CPU 的使用信息。

return {
        "cpu_percent": psutil.cpu_percent(interval=1),
  • psutil.cpu_percent(interval=1):统计 1 秒钟内 CPU 的总体使用率(百分比)。
 "cpu_cores": psutil.cpu_count(logical=False),
  • psutil.cpu_count(logical=False):获取物理核心数,不包含超线程。
 "cpu_threads": psutil.cpu_count(logical=True)
  • psutil.cpu_count(logical=True):获取逻辑核心数(包括超线程)。

返回一个包含三个键值的字典。


💾 获取内存信息

def get_memory_info():

定义函数 get_memory_info,收集内存使用情况。

    mem = psutil.virtual_memory()
  • 调用 virtual_memory() 获取当前系统的内存使用信息,返回一个包含多个字段的对象。
    return {
        "total": mem.total,
        "available": mem.available,
        "used": mem.used,
        "percent": mem.percent
    }
  • 提取并返回 total(总内存)、available(可用)、used(已用)和 percent(使用率)这几个重要指标,作为字典返回。

📁 获取磁盘使用情况

def get_disk_info():

定义函数 get_disk_info,用来收集磁盘每个分区的使用状态。

partitions = psutil.disk_partitions()
  • 获取所有磁盘分区(如 /, /boot)。
disk_info = {}
  • 初始化一个空字典,用来存储每个挂载点的使用信息。
    for p in partitions:
  • 遍历所有磁盘分区。
 usage = psutil.disk_usage(p.mountpoint)
  • 获取该分区的使用情况(总空间、已用、可用、百分比)。
  disk_info[p.mountpoint] = {
            "total": usage.total,
            "used": usage.used,
            "free": usage.free,
            "percent": usage.percent
        }
  • 把该挂载点的使用数据以字典形式存入 disk_info 中,以挂载点路径为键。
 return disk_info
  • 返回整个磁盘信息的字典。

🌐 获取网络信息

def get_network_info():

定义函数 get_network_info,收集网络数据使用情况。

 net_io = psutil.net_io_counters()
  • 获取网络接口的总体读写统计(从开机到现在)。
 return {
        "bytes_sent": net_io.bytes_sent,
        "bytes_recv": net_io.bytes_recv
    }
  • 返回已发送和接收的总字节数。

⏱️ 获取系统运行时间

def get_uptime():

定义函数 get_uptime,计算系统运行了多久。

    boot_time = datetime.datetime.fromtimestamp(psutil.boot_time())
  • psutil.boot_time() 返回系统开机时间Unix 时间戳)。
  • fromtimestamp() 将其转换为 datetime 对象。
    now = datetime.datetime.now()
  • 获取当前时间。
return str(now - boot_time).split('.')[0]
  • 计算时间差(即运行时长),去掉微秒部分并转为字符串返回。

🖥️ 获取主机名

def get_hostname():
    return socket.gethostname()

使用 socket.gethostname() 返回本机的主机名。


🔁 主程序入口

def main():

定义主函数,控制整个程序流程。

print(f"主机名: {get_hostname()}")

打印主机名。

 print(f"系统运行时间: {get_uptime()}")

打印系统开机至今的运行时间。


▶️ 打印 CPU 信息

 print("\n=== CPU 信息 ===")

打印 CPU 信息的标题。

    for k, v in get_cpu_info().items():
        print(f"{k}: {v}")
  • 遍历 CPU 信息字典并打印每项的键和值。

🧠 打印内存信息

 print("\n=== 内存 信息 ===")

标题。

 for k, v in get_memory_info().items():
        print(f"{k}: {v // (1024 * 1024)} MB")
  • 遍历内存数据,将字节转换为 MB 后打印。

💽 打印磁盘信息

    print("\n=== 磁盘 信息 ===")

标题。

 disk_info = get_disk_info()

获取磁盘信息。

 for mount, info in disk_info.items():

遍历每个挂载点及其信息。

print(f"\n挂载点: {mount}")

打印当前磁盘分区的挂载点。

for k, v in info.items():

遍历该挂载点的信息。

            if isinstance(v, (int, float)):
                print(f"  {k}: {v // (1024 * 1024)} MB" if 'percent' not in k else f"  {k}: {v}%")
            else:
                print(f"  {k}: {v}")
  • 如果值是数字,就转成 MB 打印(除了百分比)。
  • 否则直接打印。

🌐 打印网络信息

   print("\n=== 网络 信息 ===")
    net_info = get_network_info()

获取网络流量。

  print(f"已发送: {net_info['bytes_sent'] // (1024 * 1024)} MB")
  print(f"已接收: {net_info['bytes_recv'] // (1024 * 1024)} MB")

将字节转换为 MB 并打印发送和接收量。


🚀 执行入口

if __name__ == "__main__":
    main()
  • Python 程序的标准入口。
  • 如果是直接运行脚本,就执行 main()