• Post author:
  • Post category:python
  • Post comments:0评论

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

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

def get_dmi(keyword):
    """获取服务器厂商、型号、序列号、UUID信息"""
    # p = Popen(["dmidecode", "-s", keyword], stdout=PIPE, encoding="utf-8")
    # data = p.stdout.read()
    # return data.strip()
    dmi = os.popen('dmidecode -s ' + keyword).read()
    return dmi.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 str(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] | grep -Ev 'sr[0-9]*' | 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(" , ")

def output_format(k, v):
    """定义输出格式"""
    Len = 20
    filling = Len - len(k.encode('gbk'))
    return k + (" " * filling) + v

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

    for k, v in dic.items():
        print(output_format(k+':', v))

执行结果:

[root@cp-3 hard_info]# python3 hard_info.py 
服务器厂商:         Red Hat
服务器型号:         KVM
服务器序列号:       Not Specified
服务器UUID:         5e6c5126-f3d5-4428-b537-d0282362542b
主机名:             cp
IP:                 10.244.0.1 , 10.60.77.22 , 10.244.0.0
操作系统:           CentOS Linux release 7.6.1810 (Core)
CPU型号:            Intel Xeon Processor (Icelake)
物理CPU:            2
逻辑CPU:            2
总内存:             7.5 GB
磁盘:               40G*1

发表评论

验证码: + 77 = 83