FreezeJ' Blog

python使用psutil获取服务器基本信息

2020-06-01

官方文档

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020-6-1 11:28
# @Author  : FreezeJ
# @File    : get_machine_info.py
# @Software: PyCharm
# @Comment : Null

import psutil
import math
import json


def machine_info(max_percent=90, cpu_interval=0.5, none_value='none'):
    """
    :param max_percent: 最大的内存和磁盘百分比,默认为90
    :param cpu_interval: 检测cpu使用率时间,默认为0.5秒,可以设置为0瞬间返回,但是结果可能不准确
    :param none_value: 定义空值
    :return: None
    """

    def tr_gb(num):  # 转换为GB单位,ceil为向上取整
        if isinstance(num, int) or isinstance(num, float):
            return math.ceil(num / 1024.0 / 1024.0 / 1024.0)
        else:
            return none_value

    log_info_list = []  # 用于记录日志

    # CPU
    cpu_num = psutil.cpu_count()
    cpu_percent = psutil.cpu_percent(interval=cpu_interval)

    # 内存
    mem = psutil.virtual_memory()
    mem_total = mem.total
    mem_used = mem.used
    mem_buffers = mem.buffers
    mem_cached = mem.cached
    mem_free = mem.free + mem_buffers + mem_cached
    mem_percent = mem.percent

    # 磁盘
    disk = psutil.disk_partitions()
    mount_point_list = [d.mountpoint for d in disk]
    if '/data' not in mount_point_list:
        log_info_list.append("找不到data盘!")
        data_disk_total = data_disk_used = data_disk_free = data_disk_percent = none_value
        can_install_game = 'false'
    else:
        data_disk = psutil.disk_usage('/data')
        data_disk_total = data_disk.total
        data_disk_used = data_disk.used
        data_disk_free = data_disk.free
        data_disk_percent = math.ceil(data_disk.percent)
        if data_disk_percent > max_percent or tr_gb(data_disk_free) < 10:
            log_info_list.append("磁盘空间不足,剩余空间为{0}GB,无法再安装新服!".format(tr_gb(data_disk_free)))
            can_install_game = 'false'
        else:
            can_install_game = 'true'

    # 结果
    if mem_percent > max_percent or tr_gb(mem_free) < 5:
        log_info_list.append("内存不足,剩余内存为{mem_free_gb}GB,无法再安装新服!".format(mem_free_gb=tr_gb(mem_free)))
        can_install_game = 'false'
    result = {
        "mem_total_gb": tr_gb(mem_total),
        "mem_used_gb": tr_gb(mem_used),
        "mem_free_gb": tr_gb(mem_free),
        "mem_percent": math.ceil(mem_percent),
        "data_total_gb": tr_gb(data_disk_total),
        "data_disk_used_gb": tr_gb(data_disk_used),
        "data_disk_free_gb": tr_gb(data_disk_free),
        "data_disk_percent": data_disk_percent,
        "cpu_percent": cpu_percent,
        "cpu_num": cpu_num,
        "can_install_game": can_install_game,  # 磁盘和内存有空间,可以装服
        "log_info_list": log_info_list,  # 用于记录错误,有内容就代表存在报错
    }
    print(json.dumps(result))


if __name__ == '__main__':
    machine_info(max_percent=90, cpu_interval=0.5)

Tags: Python
使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏