• 实现的功能

    搜集系统消息,有生产商,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]))

最新文章

  1. iOS 学习 - 16.绘制虚线
  2. 被swoole坑哭的PHP程序员
  3. 循序渐进Python3(十)-- 3 -- SqlAlchemy
  4. Netezza SQL Analytic Functions 分析函数
  5. c++ 对象的内存布局
  6. 绑定事件 addEventListener
  7. XGrid绑定(转)
  8. A - Wireless Network-poj2236(简单并查集)
  9. python-cmp()的使用
  10. ES6作用域和解构赋值
  11. 『扩展欧几里得算法 Extended Euclid』
  12. jquery的on()用法实例
  13. rad 10.2
  14. 初识Dubbo+Zookeeprt搭建SOA项目
  15. bootstrap-datepicker应用
  16. spyder里的"查找文件里的特定字符串"非常方便
  17. python 带正则的search 模块
  18. RabbitMQ.client消息队列
  19. Scala 入门详解
  20. (转) Unity3D 使用Texturepacker打包工具制作NGUI(Atlas)图集

热门文章

  1. Client IP Address Client Identification
  2. 为什么在Java中不使用finalize()方法
  3. python基础-第四篇-4.2文件操作
  4. Web性能测试通用标准
  5. 项目删除又重新clone,未重新进入项目目录或重启terminal,导致git命令或其他命令报 目录不存在的错误
  6. LInux中的文件系统1
  7. python常见模块之序列化(json与pickle以及shelve)
  8. Linux包管理及yum
  9. Spark2.0机器学习系列之11: 聚类(幂迭代聚类, power iteration clustering, PIC)
  10. kettle转换添加hbase-output无法获取hbase表