Python例子

python例子-查看服务器硬件信息

有时候,我们在项目中需要实时监控服务器的硬件信息,那么python该如何获取呢,废话不多说,直接撸上代码。

import os
import platform
import re
from datetime import datetime
import time
import psutil

'''获取服务器信息'''


def get_server_information():
    # 主机名称
    hostname = platform.node()
    # 系统版本
    system_version = platform.platform()
    # python版本
    python_version = platform.python_version()
    # 逻辑cpu数量
    cpu_count = psutil.cpu_count()
    # cup使用率
    cpus_percent = psutil.cpu_percent(interval=0.1)
    # 内存
    memory_information = psutil.virtual_memory()
    # 内存使用率
    memory_usage = memory_information.percent
    memory_used = str(round(memory_information.used / 1024 / 1024))
    memory_total = str(round(memory_information.total / 1024 / 1024))
    memory_free = str(round(memory_information.free / 1024 / 1024))
    # 磁盘信息
    disk_partitions_list = []
    # 判断是否在容器中
    if not os.path.exists('/.dockerenv'):
        disk_partitions = psutil.disk_partitions()
        for i in disk_partitions:
            a = psutil.disk_usage(i.device)
            disk_partitions_dict = {
                'device-系统盘位置': i.device,
                'fstype-硬盘类型': i.fstype,
                'total-总容量': str(round(a.total / 1024 / 1024)),
                'used-已用硬盘': str(round(a.used / 1024 / 1024)),
                'free-空闲硬盘': str(round(a.free / 1024 / 1024)),
                'percent已用比例': a.percent
            }
            disk_partitions_list.append(disk_partitions_dict)
    # 开机时间
    boot_time = datetime.fromtimestamp(psutil.boot_time()).replace(microsecond=0)
    up_time = datetime.now().replace(microsecond=0) - boot_time
    up_time_list = re.split(r':', str(up_time))
    up_time_format = " {} 小时{} 分钟{} 秒".format(up_time_list[0], up_time_list[1], up_time_list[2])
    # 当前时间
    time_now = time.strftime('%H:%M:%S ', time.localtime(time.time()))
    data = {}
    data["hostname-主机名称"] = hostname
    data["system_version-系统版本"] = system_version
    data["python_version-python版本"] = python_version
    data["cpus_percent-cup使用率"] = cpus_percent
    data["已用内容-memory_usage"] = memory_usage
    data["cpu_count-CPU核数"] = cpu_count
    data["memory_used-已用内存"] = memory_used
    data["memory_total-总内存容量"] = memory_total
    data["memory_free-空闲内存"] = memory_free
    data["boot_time-服务器时间"] = boot_time
    data["up_time_format-服务器运行时间"] = up_time_format
    data["disk_partitions_list"] = disk_partitions_list
    data["time_now"] = time_now
    return data
print(get_server_information())


最后修改:2021-10-20 11:43:05