用python收集系统信息

  • 实现的功能
    搜集系统消息,有生产商,CPU型号,核数,内存,主机名,发行版名称
  • 可运行的系统
    目前已在RHEL, Ubuntu, Archlinux上测试通过
  • 获取不同发行版主机名逻辑判断思路分析
    大家肯定都知道,RHEL的主机名配置文件和Ubuntu的不一样,可是Archlinux的和Ubuntu的又不一样,所以这里就将不同操作系统的主机名配置文件和操作系统的issue做了一个映射
    主要是将不同系统的系统名和对应的配置文件及存放在一个字典[ os_type ]结构中,后续有需要可以再扩展,而下面的的逻辑代码则不需要改变[ parseCfg() ],从字典中循环取数据,如果取到则退出的配置文件

运行结果类似如下:

       key: value
   product: VMware Virtual Platform
 modelName: Intel(R) Xeon(R) CPU E5-2620 v3 @ 2.40GHz
  totalMem: 1.5 GB
   cpuCore: 2
    vender: VMware, Inc.
  hostName: archlinux.vsphere
distroName: Arch Linux
        SN: VMware-56 4d b9 19 26 63 ad ae-41 f3 5c 3c 34 66 ec bd
#!/usr/bin/env python
# -*- encoding: utf-8 -*-

''' 可以在多linux平台下的多种机器下工作,需要添加相应的键值对儿在os_type字典里面 '''

from subprocess import Popen, PIPE


# 定义操作系统主机名字段字典, 在获取不同类型主机名配置文件的时候使用
os_type = {'archlinux': ['Arch Linux', '/etc/hostname'],
           'ubuntu': ['Ubuntu', '/etc/hostname'],
           'CentOS release': ['CentOS release', '/etc/sysconfig/network']
           }

def parseCfg(osName):
        ' 通过不同的主机名,返回对应的主机名的配置文件位置 '
	for type in os_type:
		if osName.startswith( os_type[type][0] ):
			cfg = os_type[ type ][ 1 ]
			return cfg

def getHostInfo(command):
	''' @args: command 输入要运行的系统命令
		@return: 返回一个长的字符串
	'''
	p = Popen([command], stdout=PIPE)
	data = p.stdout.read()
	
	return data


def parseHostInfo(data):
	NEWLINE = '\n'
	parsedData = []
	eachSection = ''
	''' regenerate a list, remove the NULL element
		@args: data is a long string
		@return: all of sections list
	'''
	data = [i for i in data.split('\n') if i]
	
	for eachLine in data:
		if eachLine[0].strip():
			parsedData.append(eachSection)
			eachSection = eachLine + NEWLINE
		else:
			eachSection = eachSection + eachLine + NEWLINE
	parsedData.append(eachSection)
	
	return [i for i in parsedData if i]


def parseIPInfo(parsedData):
	dic = {}
	data = [i for i in parsedData if i and not i.startswith('lo')]
	
	for lines in data:
		lineLst = lines.split('\n')
		devname = lineLst[0].split(':')[0]
		ipaddr = lineLst[1].split()[1]
		macaddr = lineLst[3].split()[1]
		dic[devname] = [ipaddr, macaddr]
	return dic


def parseDMIInfo(parsedData):
	'''
	:param parsedData:
	:return:
	'''
	dmi_result = {}
	data = [i for i in parsedData if i.startswith('System Information')]
	data = [i for i in data[0].split('\n')[1:] if i]
	'生成一个大列表,每个元素也是一个列表,且仅有两个元素,所以下面可以直接生成一个字典数据结构'
	l_list = [i.strip().split(':') for i in data]
	sys_info_dic = dict(l_list)
	dmi_result['vender'] = sys_info_dic['Manufacturer'].strip()
	dmi_result['product'] = sys_info_dic['Product Name'].strip()
	dmi_result['SN'] = sys_info_dic['Serial Number'].strip()
	
	return dmi_result


def getDistroName():
	with open('/etc/issue') as fd:
		distroName = ' '.join(fd.read().strip().split()[:2])
	return {'distroName': distroName}

def getHostname(fn, osVer):
	with open(fn) as fd:
		host = fd.read()
		if osVer.startswith('Arch Linux') or osVer.startswith('Ubuntu'):
			hostName = host.strip()
			return {'hostName': hostName}
		if osVer == 'CentOS release':
			host = host.strip().split('\n')
			for i in host:
				if i.startswith('HOSTNAME'):
					hostName = i.split('=')[1]
					return {'hostName': hostName}

def getMeminfo():
	with open('/proc/meminfo') as fd:
		for eachLine in fd:
			if eachLine.startswith('MemTotal'):
				totalMem = eachLine.split(':')[1].strip()
				totalMem = '%.1f' % (float(totalMem.split()[0]) / 1024.0 / 1024)
	return {'totalMem': str(totalMem) + ' GB'}


def getCPUInfo():
	with open('/proc/cpuinfo') as fd:
		for eachLine in fd:
			if eachLine.startswith('cpu cores'):
				cpuCore = eachLine.split(':')[1].strip()
				continue
			if eachLine.startswith('model name'):
				modelName = eachLine.split(':')[1].strip()
		return {'cpuCore': cpuCore, 'modelName': modelName}

if __name__ == '__main__':
	dic = {}
	cfg = '/etc/sysconfig/network'
	data = getHostInfo('dmidecode')
	dmiLst = parseHostInfo(data)
	' dmi info '
	dmiInfo = parseDMIInfo(dmiLst)
	memInfo = getMeminfo()
	osVer = getDistroName()
	osName = osVer['distroName']
	cfg = parseCfg(osName)
	hostInfo = getHostname(cfg, osName)
	cpuInfo = getCPUInfo()
	
	dic.update(dmiInfo)
	dic.update(hostInfo)
	dic.update(memInfo)
	dic.update(osVer)
	dic.update(cpuInfo)
	
	print('%10s: %s' % ('key', 'value'))
	for key in dic.items():
		print('%10s: %s' % (key[0], key[1]))
posted @ 2017-03-25 10:59  ZhangRuoxu  阅读(1815)  评论(0编辑  收藏  举报