统计服务器的相关配置信息

该脚本主要用来统计CentOS,RedHat 6~7系统版本的服务器基础信息,方便自己检查新服的配置。

#!/usr/bin/python
# coding: utf8

from subprocess import Popen, PIPE
import time
import re
import os


# 获取主机名
def host_name():
    hostname = Popen(["hostname"], stdout=PIPE)
    hostname = hostname.stdout.read()
    return hostname

# 获取操作系统版本
def os_version():
    with open("/etc/redhat-release") as f:
        os_version = f.read()
    return os_version

# 获取操作系统内核版本
def os_core_version():
    os_core_version = Popen(["uname", "-r"], stdout=PIPE)
    os_core_version = os_core_version.stdout.read()
    return os_core_version

# 获取CPU相关信息
def cpu_info():
    core_number = []
    with open("/proc/cpuinfo") as cpu_info:
        for i in cpu_info:
            if i.startswith("processor"):
                core_number.append(i)
            if i.startswith("model name"):
                cpu_mode = i.split(":")[1]
    return len(core_number), cpu_mode

# 获取内存相关信息
def mem_info():
    with open("/proc/meminfo") as mem_info:
        for i in mem_info:
            if i.startswith("MemTotal"):
                mentotal = i.split(" ")[-2:]
                mentotal = ' '.join(mentotal)
    return mentotal

# 获取服务器硬件相关信息
def bios_info():
    bios_info = Popen(["dmidecode", "-t", "system"], stdout=PIPE)
    bios_info = bios_info.stdout.readlines()

    for i in bios_info:
        if "Manufacturer" in i:
            manufacturer = i.split(":")[1]
        if "Serial Number" in i:
            serialnumber = i.split(":")[1]
    return manufacturer, serialnumber

# 获取服务器的时间信息
def Time_info():
    time_info = time.strftime('%Y-%m-%d %A %X', time.localtime())
    # time_info = Popen(["date", "-R"], stdout=PIPE)
    # time_info = time_info.stdout.read()
    return time_info

# 使用ifconfig获取网卡信息
def getIfconfig():
    p = Popen(['ifconfig'], stdout=PIPE)
    data = p.stdout.read().split('\n\n')
    return [i for i in data if i and not i.startswith('lo')]

# 对ifconfig的输出信息进行筛选
def parseIfconfig(data):
    dic = {}
    for line in data:
        re_devname = re.compile(r'(\w+).*Link encap', re.M)
        re_macaddr = re.compile(r'HWaddr\s([0-9A-F:]{17})', re.M)
        # re_ipaddr = re.compile(r'inet addr: ([\d\.]{7, 15})', re.M)
        re_ipaddr = re.compile(r'inet addr:([\d\.]{7,15})', re.M)
        devname = re_devname.search(line)
        mac = re_macaddr.search(line)
        ip = re_ipaddr.search(line)

        if devname:
            devname = devname.group(1)
        else:
            devname = ''

        if mac:
            mac = mac.group(1)
        else:
            mac = ''

        if ip:
            ip = ip.group(1)
        else:
            ip = ''
        dic[devname] = [mac, ip]
    return dic

# 获取磁盘相关信息
def disk_info():
    disk_info = Popen(["df", "-h"], stdout=PIPE)
    disk_info = disk_info.stdout.read()
    return disk_info

# 格式对齐函数
def myAlign(string, length=0):
    if length == 0:
        return string
    slen = len(string)
    re = string
    if isinstance(string, str):
        placeholder = ' '
    else:
        placeholder = u' '
    while slen < length:
        re += placeholder
        slen += 1
    return re

if __name__ == '__main__':
    # 初始化相关对象
    hostname = host_name()
    osversion = os_version()
    oscoreversion = os_core_version()
    totalmem = mem_info()
    cpunumber, cpumode = cpu_info()
    manufacturer, serialnumber = bios_info()
    timeinfo = Time_info()
    data = getIfconfig()
    ipinfo = parseIfconfig(data)
    diskinfo = disk_info()

    width = 60
    print '%s' %("".center(width, '='))
    print myAlign(u"服务器时间及时区", 10) + ":" + myAlign(str(timeinfo))
    print myAlign(u"主机名", 10) + ":" + myAlign(str(hostname)),
    print myAlign(u"系统版本", 10) + ":" + myAlign(str(osversion)),
    print myAlign(u"系统内核版本", 10) + ":" + myAlign(str(oscoreversion)),
    print myAlign(u"总内存", 10) + ":" + myAlign(str(totalmem)),
    print myAlign(u"CPU生产商", 10) + "   :" + myAlign(cpumode),
    print myAlign(u"CPU总核心数", 10) + "   :" + myAlign(str(cpunumber))
    print myAlign(u"服务器生产商", 10) + ":" + myAlign(str(manufacturer)),
    print myAlign(u"服务器序列号", 10) + ":" + myAlign(str(serialnumber)),
    print ""
    print '%s' %("".center(width, '='))
    print '%s' %("网卡信息".center(width, '-'))
    for x in ipinfo:
        print '%s' %("".center(width, '-'))
        print myAlign(u"网卡名", 10) + ":" + myAlign(str(x))
        print myAlign(u"物理地址", 10) + ":" + myAlign(str(ipinfo[x][0]))
        print myAlign(u"IP地址", 10) + "  :" + myAlign(str(ipinfo[x][1]))
    print ""
    print '%s' %("".center(width, '='))
    print '%s' %("磁盘分区信息".center(width, '-'))
    print diskinfo
    print '%s' %("".center(width, '='))
  • 输出结果显示


    脚本输出结果

推荐阅读更多精彩内容

  • linux资料总章2.1 1.0写的不好抱歉 但是2.0已经改了很多 但是错误还是无法避免 以后资料会慢慢更新 大...
    O感悟人生O阅读 7,453评论 2 27
  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 3,568评论 3 7
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 76,042评论 12 117
  • 特立独行是什么? 特:独特;立:立身。形容人的志行高洁,不同流俗。 朋友问我说:“太阳太大了,你说我上班要不要买一...
    请叫我徐老师x阅读 243评论 16 8
  • 只是个人的一些想法,大家看看就好。 主要讨论万元左右的单反或微单的视频拍摄功能,拍照功能暂不讨论。 2016已经开...
    星夜7632阅读 3,333评论 0 2