首页 > 代码库 > Python收集主机信息
Python收集主机信息
Python收集linux主机信息,需要安装dmidecode命令,yum -y install dmidecode
#!/usr/bin/env python # coding=utf-8 from subprocess import Popen, PIPE #获取ifconfig命令信息 def getIfconfig(): p = Popen([‘ifconfig‘], stdout=PIPE) data = p.stdout.read().decode() return data #获取dmidecode命令信息 def getDmi(): p = Popen([‘dmidecode‘], stdout=PIPE) data = p.stdout.read().decode() return data #处理data数据输出为list并去掉空 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 [i for i in parsed_data if i] #处理ifconfig数据并获取eth1的IP地址 def parseIfocnfig(parsed_data): dic = {} parsed_data = [ i for i in parsed_data if i.startswith(‘eth1‘)] for lines in parsed_data: line_list = lines.split(‘\n‘) devname = line_list[0].split()[0] macaddr = line_list[2].split()[1] ipaddr = line_list[1].split()[1] break dic[‘ip‘] = ipaddr return dic #处理dmidecode数据获取信息 def paeseDmi(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‘][:8] return dic #获取hostname 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} #获取操作系统 def getOSver(f): with open(f) as fd: for line in fd: osver = line.strip() break return {‘osver‘: osver} #获取CPU数 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[3]+‘ ‘+ cpu_model[-1] return {‘cpu_num‘: num, ‘cpu_model‘: cpu_model} #获取内存大小 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} def main(): dic = {} ip = parseIfocnfig(parseData(getIfconfig())) dmi = paeseDmi(parseData(getDmi())) osver = getOSver(‘/etc/issue‘) hostname = getHostname(‘/etc/sysconfig/network‘) cpu = getCpu(‘/proc/cpuinfo‘) memory = getMemory(‘/proc/meminfo‘) # lines = [ip, dmi, hostname, osver, cpu, memory] # for i in lines: # dic.update(i) dic.update(ip) dic.update(dmi) dic.update(hostname) dic.update(osver) dic.update(cpu) dic.update(memory) print(dic) if __name__ == ‘__main__‘: main()
本文出自 “Linux运维” 博客,请务必保留此出处http://xtbao.blog.51cto.com/7482722/1889779
Python收集主机信息
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。