• Post author:
  • Post category:python
  • Post comments:0评论
Like
Like Love Haha Wow Sad Angry

脚本内容,主要用来练练手:

#!/usr/bin/env python3
# Author: cp
"""
收集Linux服务器信息:
服务器厂商、型号、序列号、主机名称、IP、系统版本、CPU信息、内存信息、磁盘信息
"""
from subprocess import Popen, PIPE
import os

def get_dmi(keyword):
    """获取服务器厂商、型号、序列号信息"""
    p = Popen(["dmidecode", "-s", keyword], stdout=PIPE, encoding="utf-8")
    data = p.stdout.read()
    return data.strip()

def get_hostname():
    """获取主机名"""
    hostname = os.popen('hostname').read()
    return hostname.strip()

def get_os():
    """操作系统信息"""
    os_version = os.popen('hostnamectl | grep "Operating System"').read()
    if "CentOS" in os_version:
        with open('/etc/redhat-release') as f:
            return f.read().strip()
    else:
        with open('/etc/issue') as f:
            return f.read().strip()

def get_cpu(keyword):
    """获取CPU的型号、物理CPU数量和逻辑CPU数量"""
    cpu_info = {}
    cpu_info["cpu_num_p"] = 0
    cpu_info["cpu_num_l"] = 0
    cpu_set = set()
    with open('/proc/cpuinfo') as f:
        for line in f:
            if line.startswith('model name'):
                cpu_info['cpu_model'] = line.split(':')[1].strip()
            if line.startswith('processor'):
                cpu_info['cpu_num_l'] += 1
            if line.startswith('physical id'):
                cpu_set.add(line.split(':')[1].strip())

    cpu_info["cpu_num_p"] = len(cpu_set)
    return cpu_info[keyword]

def get_memory():
    """获取内存"""
    with open('/proc/meminfo') as f:
        for line in f:
            if line.startswith('MemTotal'):
                mem = int(line.split()[1].strip())
                break
    mem = '%.3s' % (mem / 1024 / 1024) + ' GB'
    return mem

def get_disk():
    """磁盘统计"""
    disk_list = os.popen("lsblk | grep ^[a-z] | awk '{print$4}'").read().split()
    disk_set = set(disk_list)
    disk_dict = {}

    for i in disk_set:
        c = disk_list.count(i)
        disk_dict[i] = c
    # return disk_dict
    aa = ""
    for k, v in disk_dict.items():
        a = f"{k}*{v}"
        aa += " , " + a
    return aa.strip(" , ")

def get_ip():
    """获取ip信息"""
    # 获取ifconfig命令输出,并根据空行分段
    p = os.popen('ifconfig')
    data = p.read().split('\n\n')
    ip_list = []
    for lines in data:
        line_list = lines.split('\n')
        if ('RUNNING' in line_list[0]) and ('inet ' in line_list[1]) and ("lo" not in line_list[0]):
            ipaddr = line_list[1].strip().split()[1]
            ip_list.append(ipaddr)
    # return ip_list
    a = ""
    for i in ip_list:
        a += " , " + i
    return a.strip(" , ")

if __name__ == '__main__':
    dic = {}
    dic["服务器厂商"] = get_dmi("system-manufacturer")
    dic["服务器型号"] = get_dmi("system-product-name")
    dic["服务器序列号"] = get_dmi("system-serial-number")
    dic["主机名"] = get_hostname()
    dic["IP"] = get_ip()
    dic["操作系统"] = get_os()
    dic["CPU型号"] = get_cpu("cpu_model")
    dic["CPU数量(物理)"] = get_cpu("cpu_num_l")
    dic["CPU数量(逻辑)"] = get_cpu("cpu_num_p")
    dic["总内存"] = get_memory()
    dic["磁盘"] = get_disk()

    for k, v in dic.items():
        print('%s:\t\t%s' % (k, v))

执行结果:

[root@cp-3 hard_info]# python3 hard_info.py 
服务器厂商:     RDO
服务器型号:     OpenStack Compute
服务器序列号:   26032d40-eb5c-41a8-871e-6e968d4fc6bf
主机名:         cp-3.novalocal
IP:             10.0.0.14
操作系统:       CentOS Linux release 7.6.1810 (Core)
CPU型号:        Intel Xeon Processor (Skylake, IBRS)
CPU数量(物理):   2
CPU数量(逻辑):   2
总内存:          3.7 GB
磁盘:            200G*1
Like
Like Love Haha Wow Sad Angry

发表评论