收集主机的以下信息,并以字典形式输出。
1、主机名:hostname
2、IP地址:ip
3、操作系统版本:osver
4、服务器厂商:vendor
5、服务器型号:product
6、服务器序列号:sn
7、cpu型号:cpu_model
8、cpu核数:cpu_num
9、内存大小:memory
代码如下:
vim collect_info.py
#!/ usr / bin / env python
从子流程导入Popen,PIPE
def getIfconfig():
p = Popen(['ifconfig'],stdout = PIPE)
数据= p.stdout.read()
返回数据
def getDmi():
p = Popen(['dmidecode'],stdout = PIPE)
数据= p.stdout.read()
返回数据
def parseData(数据):
parsed_data = []
new_line =''
数据= [如果i为i,则为data.split('\ n')中的i]
用于输入数据:
如果line [0] .split():
parsed_data.append(new_line)
new_line =行+'\ n'
其他:
new_line + =线+'\ n'
parsed_data.append(new_line)
返回[如果我而不是i.startswith('lo'),则在parsed_data中为i表示i]
def parseIfconfig(parsed_data):
dic = {}
对于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]
打破
dic ['ip'] = ipaddr
返回dic
def parseDmi(parsed_data):
dic = {}
parsed_data = [如果i.startswith('System Information'),则i在parsed_data中为i
parsed_data = [i for parsed_data [0] .split('\ n')[1:],如果i]
dmi_dic = dict([i.strip()。split(':')for parsed_data中的i]
dic ['vendor'] = dmi_dic ['Manufacturer']。strip()
dic ['product'] = dmi_dic ['Product Name']。strip()
dic ['sn'] = dmi_dic ['序列号'] .strip()[:15]
返回dic
def getHostname(f):
使用open(f)作为fd:
对于fd中的行:
如果line.startswith('HOSTNAME'):
主机名= line.split('=')[1] .strip()
打破
返回{'hostname':hostname}
def getOsver(f):
使用open(f)作为fd:
对于fd中的行:
osver = line.strip()
打破
返回{'osver':osver}
def getCpu(f):
num = 0
使用open(f)作为fd:
对于fd中的行:
如果line.startswith('processor'):
num + = 1
如果line.startswith('型号名称'):
cpu_model = line.split(':')[1] .split()
cpu_model = cpu_model [0] +''+ cpu_model [-1]
返回{'cpu_num':num,'cpu_model':cpu_model}
def getMemory(f):
使用open(f)作为fd:
对于fd中的行:
如果line.startswith('MemTotal'):
mem = int(line.split()[1] .strip())
打破
mem =“%s”%int(mem / 1024.0)+'M'
返回{'memory':mem}
如果__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)
主机名= getHostname('/ etc / sysconfig / network')
osver = getOsver('/ etc / issue')
cpu = getCpu('/ proc / cpuinfo')
mem = getMemory('/ proc / meminfo')
dic.update(ip)
dic.update(dmi)
dic.update(主机名)
dic.update(osver)
dic.update(cpu)
dic.update(内存)
打印骰子
验证结果如下: