设为首页收藏本站

IT联盟

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 1542|回复: 3

[学习笔记] python获取主机信息

[复制链接]

232

主题

242

帖子

3605

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
3605

管理员最佳新人活跃会员热心会员推广达人灌水之王突出贡献优秀版主荣誉管理论坛元老

发表于 2016-12-6 10:05:48 | 显示全部楼层 |阅读模式
[Python] 纯文本查看 复制代码
#!/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()
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|IT技术联盟论坛 ( 京ICP备15062632  点击这里给我发消息

GMT+8, 2019-12-15 13:20 , Processed in 0.083724 second(s), 31 queries .

Powered by Discuz! X3.2 Licensed Designed By

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表