收集主机信息,包括:
1、主机名:hostname
2、IP地址:ip
3、操作系统版本:osver
4、服务器厂商:vendor
5、服务器型号:product
6、服务器序列号:sn
7、cpu型号:cpu_module
8、cpu核心数量:cpu_num
9、内存大小
收集IP信息
[root@133 systeminformation]# vim sysinformation.py
from subprocess import Popen,PIPE
def getIfconfig():
p = Popen(['ifconfig'],stdout=PIPE)
data = p.stdout.read()
return data
def getDmi():
p = Popen(['dmidecode'],stdout = PIPE)
data = p.stdout.read()
return data
def parseData(data):
parsed_data = []
new_line = ''
data = [i for i in data.split('\n') if i ]
for line in data:
if line[0].strip():
parsed_data.append(new_line)
new_line = line + '\n'
else:
new_line +=line + '\n'
parsed_data.append(new_line)
return parsed_data
def parseIfconfig(parsed_data):
dic = {}
tuple_addr= ('lo','vir','vnet','em3','em4')
parsed_data = [i for i in parsed_data if i and not i.startswith('tuple_addr')]
for lines in parsed_data:
line_list = lines.split('\n')
devname = line_list[0].split()[0]
macaddr = line_list[0].split()[-1]
ipaddr = line_list[1].split()[1].split(':')[1]
break
dic ['ip'] = [devname, ipaddr, macaddr]
return dic
if __name__ == "__main__":
data = getIfconfig()
parsed_data = parseData(data)
print parseIfconfig(parsed_data)
[root@133 systeminformation]# python sysinformation.py
{'ip': ['br1', '112.65.140.133', 'A4:BA:DB:20:93:23']}
收集System Information信息
[root@133 systeminformation]# vim sysinformation.py
return data
def parseData(data):
parsed_data = []
new_line = ''
data = [i for i in data.split('\n') if i ]
for line in data:
if line[0].strip():
parsed_data.append(new_line)
new_line = line + '\n'
else:
new_line +=line + '\n'
parsed_data.append(new_line)
return parsed_data
def parseIfconfig(parsed_data):
dic = {}
tuple_addr= ('lo','vir','vnet','em3','em4')
parsed_data = [i for i in parsed_data if i and not i.startswith(tuple_addr)]
for lines in parsed_data:
line_list = lines.split('\n')
devname = line_list[0].split()[0]
macaddr = line_list[0].split()[-1]
ipaddr = line_list[1].split()[1].split(':')[1]
break
dic['ip'] = devname,ipaddr,macaddr
return dic
def parseDmi(parsed_data):
dic = {}
parsed_data = [i for i in parsed_data if i.startswith('System Information')]
return parsed_data
if __name__ == "__main__":
data_ip = getIfconfig()
parsed_data_ip = parseData(data_ip)
print parseIfconfig(parsed_data_ip)
data_dmi = getDmi()
parsed_data_dmi = parseData(data_dmi)
print parseDmi(parsed_data_dmi)
[root@133 systeminformation]# python sysinformation.py #system information是一个只有一个元素的大的列表
{'ip': ('br1', '112.65.140.133', 'A4:BA:DB:20:93:23')}
['System Information\n\tManufacturer: Dell Inc.\n\tProduct Name: PowerEdge R710\n\tVersion: Not Specified\n\tSerial Number: 4HBDT2X\n\tUUID: 4C4C4544-0048-4210-8044-B4C04F543258\n\tWake-up Type: Power Switch\n\tSKU Number: Not Specified\n\tFamily: Not Specified\n']
[root@133 systeminformation]# vim sysinformation.py
return data
def parseData(data):
parsed_data = []
new_line = ''
data = [i for i in data.split('\n') if i ]
for line in data:
if line[0].strip():
parsed_data.append(new_line)
new_line = line + '\n'
else:
new_line +=line + '\n'
parsed_data.append(new_line)
return parsed_data
def parseIfconfig(parsed_data):
dic = {}
tuple_addr= ('lo','vir','vnet','em3','em4')
parsed_data = [i for i in parsed_data if i and not i.startswith(tuple_addr)]
for lines in parsed_data:
line_list = lines.split('\n')
devname = line_list[0].split()[0]
macaddr = line_list[0].split()[-1]
ipaddr = line_list[1].split()[1].split(':')[1]
break
dic['ip'] = devname,ipaddr,macaddr
return dic
def parseDmi(parsed_data):
dic = {}
parsed_data = [i for i in parsed_data if i.startswith('System Information')]
return parsed_data[0] #把大的列表转为一个字符串
if __name__ == "__main__":
data_ip = getIfconfig()
parsed_data_ip = parseData(data_ip)
print parseIfconfig(parsed_data_ip)
data_dmi = getDmi()
parsed_data_dmi = parseData(data_dmi)
print parseDmi(parsed_data_dmi)
[root@133 systeminformation]# python sysinformation.py
{'ip': ('br1', '112.65.140.133', 'A4:BA:DB:20:93:23')}
System Information #把大的列表转为一个字符串,结果如下:
Manufacturer: Dell Inc.
Product Name: PowerEdge R710
Version: Not Specified
Serial Number: 4HBDT2X
UUID: 4C4C4544-0048-4210-8044-B4C04F543258
Wake-up Type: Power Switch
SKU Number: Not Specified
Family: Not Specified
def parseDmi(parsed_data):
dic = {}
parsed_data = [i for i in parsed_data if i.startswith('System Information')]
return parsed_data[0].split('\n')#使用\n作为切割符号,结果是列表,有很多元素,而不是一个元素
[root@133 systeminformation]# python sysinformation.py
{'ip': ('br1', '112.65.140.133', 'A4:BA:DB:20:93:23')}
['System Information', '\tManufacturer: Dell Inc.', '\tProduct Name: PowerEdge R710', '\tVersion: Not Specified', '\tSerial Number: 4HBDT2X', '\tUUID: 4C4C4544-0048-4210-8044-B4C04F543258', '\tWake-up Type: Power Switch', '\tSKU Number: Not Specified', '\tFamily: Not Specified', '']
[root@133 systeminformation]#
#使用[1:]丢弃列表第一个元素:'System Information'
def parseDmi(parsed_data):
dic = {}
parsed_data = [i for i in parsed_data if i.startswith('System Information')]
return parsed_data[0].split('\n')[1:]
[root@133 systeminformation]# python sysinformation.py
{'ip': ('br1', '112.65.140.133', 'A4:BA:DB:20:93:23')}
['\tManufacturer: Dell Inc.', '\tProduct Name: PowerEdge R710', '\tVersion: Not Specified', '\tSerial Number: 4HBDT2X', '\tUUID: 4C4C4544-0048-4210-8044-B4C04F543258', '\tWake-up Type: Power Switch', '\tSKU Number: Not Specified', '\tFamily: Not Specified', '']
#使用if i去掉最后一个空元素‘ ’,使用dict函数将列表元素转换为字典
def parseDmi(parsed_data):
dic = {}
parsed_data = [i for i in parsed_data if i.startswith('System Information')]
parsed_data = [i for i in parsed_data[0].split('\n')[1:] if i]
return dict ([i.strip().split(':') for i in parsed_data])
[root@133 systeminformation]# python sysinformation.py #输出全为字典元素,key-value,然后把指定的key赋值给需要的key即可输出value
{'ip': ('br1', '112.65.140.133', 'A4:BA:DB:20:93:23')}
{'SKU Number': ' Not Specified', 'UUID': ' 4C4C4544-0048-4210-8044-B4C04F543258', 'Family': ' Not Specified', 'Serial Number': ' 4HBDT2X', 'Version': ' Not Specified', 'Product Name': ' PowerEdge R710', 'Wake-up Type': ' Power Switch', 'Manufacturer': ' Dell Inc.'}
#dic ['vender'] = dmi_dic['Manufacturer'] 这是把dmi_dic字典key和value Manufacturer:Dell Inc. 赋值给字典给dic字典的 vender,其它同理,最后输出dic,即输出三个key value的字典dic内容
def parseDmi(parsed_data):
dic = {}
parsed_data = [i for i in parsed_data if i.startswith('System Information')]
parsed_data = [i for i in parsed_data[0].split('\n')[1:] if i]
dmi_dic = dict ([i.strip().split(':') for i in parsed_data])
dic ['vender'] = dmi_dic['Manufacturer']
dic ['product'] = dmi_dic['Product Name']
dic ['sn'] = dmi_dic['Serial Number']
return dic
[root@133 systeminformation]# python sysinformation.py
{'ip': ('br1', '112.65.140.133', 'A4:BA:DB:20:93:23')}
{'vender': ' Dell Inc.', 'product': ' PowerEdge R710', 'sn': ' 4HBDT2X'}
#发现value前面有空格,使用strip()删除空格
def parseDmi(parsed_data):
dic = {}
parsed_data = [i for i in parsed_data if i.startswith('System Information')]
parsed_data = [i for i in parsed_data[0].split('\n')[1:] if i]
dmi_dic = dict ([i.strip().split(':') for i in parsed_data])
dic ['vender'] = dmi_dic['Manufacturer'].strip()
dic ['product'] = dmi_dic['Product Name'].strip()
dic ['sn'] = dmi_dic['Serial Number'].strip()
return dic
[root@133 systeminformation]# python sysinformation.py
{'ip': ('br1', '112.65.140.133', 'A4:BA:DB:20:93:23')}
{'vender': 'Dell Inc.', 'product': 'PowerEdge R710', 'sn': '4HBDT2X'}
下面是收集到所有的信息,以key value的形式保存在字典中
cat sysinformation.py
#!/usr/bin/env python
from subprocess import Popen,PIPE
def getIfconfig():
p = Popen(['ifconfig'], stdout=PIPE)
data = p.stdout.read()
return data
def getDmi():
p = Popen(['dmidecode'], stdout = PIPE)
data = p.stdout.read()
return data
def parseData(data):
parsed_data = []
new_line = ''
data = [i for i in data.split('\n') if i ]
for line in data:
if line[0].strip():
parsed_data.append(new_line)
new_line = line + '\n'
else:
new_line +=line + '\n'
parsed_data.append(new_line)
return parsed_data
def parseIfconfig(parsed_data):
dic = {}
tuple_addr= ('lo','vir','vnet','em3','em4')
parsed_data = [i for i in parsed_data if i and not i.startswith(tuple_addr)]
for lines in parsed_data:
line_list = lines.split('\n')
devname = line_list[0].split()[0]
macaddr = line_list[0].split()[-1]
ipaddr = line_list[1].split()[1].split(':')[1]
break
dic['ip'] = devname,ipaddr,macaddr
return dic
def parseDmi(parsed_data):
dic = {}
parsed_data = [i for i in parsed_data if i.startswith('System Information')]
parsed_data = [i for i in parsed_data[0].split('\n')[1:] if i]
dmi_dic = dict ([i.strip().split(':') for i in parsed_data])
dic ['vender'] = dmi_dic['Manufacturer'].strip()
dic ['product'] = dmi_dic['Product Name'].strip()
dic ['sn'] = dmi_dic['Serial Number'].strip()
return dic
#获取主机名信息:/etc/sysconfig/network
def getHostname(f):
with open(f) as fd:
for line in fd:
if line.startswith('HOSTNAME'):
hostname = line.split('=')[1].strip()
break
return {'hostname':hostname}
#获取OS版本信息:打开文件/etc/issue
def getOSver(f):
with open(f) as fd:
for line in fd:
osver = line.strip()
break
return {'osver':osver}
#获取cpu信息:/proc/cpuinfo
def getCpu(f):
num = 0
with open(f) as fd:
for line in fd:
if line.startswith('processor'):
num +=1
if line.startswith('model name'):
cpu_model = line.split(':')[1].split()
cpu_model = cpu_model[0] + ' '+cpu_model[-1]
return {'cpu_num':num, 'cpu_model':cpu_model}
#获取内存信息:/proc/meminfo
def getMemory(f):
with open(f) as fd:
for line in fd:
if line.startswith('MemTotal'):
mem = int(line.split()[1].strip())
break
mem = "%s" % int(mem/1024.0)+'M'
return {'memory':mem}
if __name__ == "__main__":
dic = {}
data_ip = getIfconfig()
parsed_data_ip = parseData(data_ip)
ip = parseIfconfig(parsed_data_ip)
data_dmi = getDmi()
parsed_data_dmi = parseData(data_dmi)
dmi = parseDmi(parsed_data_dmi)
hostname = getHostname('/etc/sysconfig/network')
osver = getOSver('/etc/issue')
cpu = getCpu('/proc/cpuinfo')
mem = getMemory('/proc/meminfo')
dic.update(ip)
dic.update(dmi)
dic.update(hostname)
dic.update(cpu)
dic.update(mem)
dic.update(osver)
print dic
[root@133 systeminformation]# python sysinformation.py
{'product': 'PowerEdge R710', 'osver': 'CentOS release 6.7 (Final)', 'sn': '4HBDT2X', 'memory': '19976M', 'cpu_num': 8, 'ip': ('br1', '112.65.140.133', 'A4:BA:DB:20:93:23'), 'vender': 'Dell Inc.', 'hostname': '133', 'cpu_model': 'Intel(R) 2.00GHz'}
注:
mem = "%s" % int(mem/1024.0)+'M'
%表示格式化字符串的格式符号。
%s,表示字符串
%d,表示整数的字符串
%x,表示16进制的字符串
%f,表示浮点数字符串
第二个%表示要格式化的对象。
这种方法可以进行类型转换。