Python 收集主机信息

写一个 python 脚本,收集以下信息 ( CentOS 6 ) :

    IP地址 <ip>
    主机名 <hostname>
    操作系统版本 <osver>
    服务器厂商 <vendor>
    服务器型号 <product>
    主板序列号 <sn>
    CPU型号 <cpu_model>
    CPU核数 <cpu_num>
    内存大小 <memory>

#!/usr/bin/env python
#-*- coding:utf-8 -*-

from subprocess import Popen, PIPE

# 获取IP地址
def getIP():
    p = Popen('ifconfig', stdout=PIPE, shell=True)
    data = p.stdout.read().split('\n\n')
    for lines in data:
        if lines.startswith('lo'):
            continue
        if lines:
            ip = lines.split('\n')[1].split()[1].split(':')[1]
            break

    return ip


# 获取主机名
def getHostname():
    p = Popen('hostname', stdout=PIPE, shell=True)
    hostname = p.stdout.read().strip()
    return hostname


# 获取操作系统版本
def getOSVersion():
    with open('/etc/issue') as fd:
        data = fd.read().split('\n')[0]
        osVer = data.split()[0] + ' ' + data.split()[2]

    return osVer


# 获取服务器硬件信息
def getHardwareInfo(name):
    cmd = ''' dmidecode --type system | grep "%s" ''' % name
    p = Popen(cmd, stdout=PIPE, shell=True)
    hardwareInfo = p.stdout.read().split(':')[1].strip()
    return hardwareInfo


# 获取CPU型号
def getCPUModel():
    with open('/proc/cpuinfo') as fd:
        for line in fd.readlines():
            if line.startswith('model name'):
                cpuModel = line.split()[3].split('(')[0]
                break

    return cpuModel


# 获取CPU核数
def getCPUNum():
    with open('/proc/cpuinfo') as fd:
        for line in fd.readlines():
            if line.startswith('cpu cores'):
                cpuNum = line.split()[3]
                break

    return cpuNum


# 获取物理内存大小
def getMemorySize():
    with open('/proc/meminfo') as fd:
        memTotal = fd.readline().split()[1]

    memSize = str(int(memTotal)/1024) + 'M'
    return memSize


if __name__ == '__main__':
    hostInfo = {}
    hostInfo['ip'] = getIP()
    hostInfo['hostname'] = getHostname()
    hostInfo['osVer'] = getOSVersion()
    hostInfo['vendor'] = getHardwareInfo('Manufacturer')
    hostInfo['product'] = getHardwareInfo('Product Name') 
    hostInfo['sn'] = getHardwareInfo('Serial Number')
    hostInfo['cpu_model'] = getCPUModel()
    hostInfo['cpu_num'] = getCPUNum()
    hostInfo['memory'] = getMemorySize()

    for key in hostInfo.keys():
        print("%s: %s" % (key, hostInfo[key]))
[root@localhost ~]$ python getHostInfo.py 
product: VMware Virtual Platform
vendor: VMware, Inc.
cpu_num: 2
ip: 192.168.119.128
hostname: localhost
cpu_model: Intel
osVer: CentOS 6.5
sn: VMware-56 4d a1 32 29 62 d8 dc-dd f9 99 6e 16 8f 65 a3
memory: 1861M

 

 

 

 

 

 

      

posted @ 2019-01-24 18:26  孔雀东南飞  阅读(724)  评论(0编辑  收藏  举报