使用 python 收集擷取 Linux 系統主機資訊

來源:互聯網
上載者:User

標籤:sysconfig   model   代碼   get   return   form   簡單   lease   span   

使用 python 代碼收集主機的系統資訊,主要:主機名稱、IP、系統版本、伺服器廠商、型號、序號、CPU資訊、記憶體等系統資訊。

#!/usr/bin/env python#encoding: utf-8‘‘‘收集主機的資訊:主機名稱、IP、系統版本、伺服器廠商、型號、序號、CPU資訊、記憶體資訊‘‘‘from subprocess import Popen, PIPEimport os,sys‘‘‘ 擷取 ifconfig 命令的輸出 ‘‘‘def getIfconfig():    p = Popen([‘ifconfig‘], stdout = PIPE)    data = p.stdout.read()    return data‘‘‘ 擷取 dmidecode 命令的輸出 ‘‘‘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 [i for i in parsed_data if i]‘‘‘ 根據輸入的段落資料分析出ifconfig的每個網卡ip資訊 ‘‘‘def parseIfconfig(parsed_data):    dic = {}    parsed_data = [i for i in parsed_data if not i.startswith(‘lo‘)]    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‘] = ipaddr    return dic‘‘‘ 根據輸入的dmi段落資料 分析出指定參數 ‘‘‘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‘‘‘ 擷取Linux系統主機名稱 ‘‘‘def getHostname():    with open(‘/etc/sysconfig/network‘) as fd:        for line in fd:            if line.startswith(‘HOSTNAME‘):                hostname = line.split(‘=‘)[1].strip()                break    return {‘hostname‘:hostname}‘‘‘ 擷取Linux系統的版本資訊 ‘‘‘def getOsVersion():    with open(‘/etc/issue‘) as fd:        for line in fd:            osver = line.strip()            break    return {‘osver‘:osver}‘‘‘ 擷取CPU的型號和CPU的核心數 ‘‘‘def getCpu():    num = 0    with open(‘/proc/cpuinfo‘) as fd:        for line in fd:            if line.startswith(‘processor‘):                num += 1            if line.startswith(‘model name‘):                cpu_model = line.split(‘:‘)[1].strip().split()                cpu_model = cpu_model[0] + ‘ ‘ + cpu_model[2]  + ‘ ‘ + cpu_model[-1]    return {‘cpu_num‘:num, ‘cpu_model‘:cpu_model}‘‘‘ 擷取Linux系統的總實體記憶體 ‘‘‘def getMemory():    with open(‘/proc/meminfo‘) as fd:        for line in fd:            if line.startswith(‘MemTotal‘):                mem = int(line.split()[1].strip())                break    mem = ‘%.f‘ % (mem / 1024.0) + ‘ MB‘    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()    osver = getOsVersion()    cpu = getCpu()    mem = getMemory()        dic.update(ip)    dic.update(dmi)    dic.update(hostname)    dic.update(osver)    dic.update(cpu)    dic.update(mem)    ‘‘‘ 將擷取到的所有資料資訊並按簡單格式對齊顯示 ‘‘‘    for k,v in dic.items():        print ‘%-10s:%s‘ % (k, v) 

 

實驗測試結果:

product   :VMware Virtual Platformosver     :CentOS release 6.4 (Final)sn        :VMware-56 4d b4 6c 05 e5 20 dc-c6 49 0c e1 e0 18 1c 75Memory    :1870 MBcpu_num   :2ip        :192.168.0.8vender    :VMware, Inc.hostname  :vipcpu_model :Intel(R) i7-4710MQ 2.50GHz

 

使用 python 收集擷取 Linux 系統主機資訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.