Use Python to collect and obtain Linux system host information

The crawler proxy IP is provided by the Sesame HTTP service provider.

The python code is used to collect the system information of the host, mainly: host name, IP, system version, server manufacturer, model, serial number, CPU information, memory and other system information.

#!/usr/bin/env python
#encoding: utf-8

'''
Gather host information:
Host name, IP, system version, server manufacturer, model, serial number, CPU information, memory information
'''

from subprocess import Popen, PIPE
import os,sys

''' Get the output of the ifconfig command'''
def getIfconfig():
    p = Popen(['ifconfig'], stdout = PIPE)
    data = p.stdout.read()
    return data

''' Get the output of the dmidecode command'''
def getDmi():
    p = Popen(['dmidecode'], stdout = PIPE)
    data = p.stdout.read()
    return data

''' Returns a list of paragraphs based on blank lines '''
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]

''' Analyze each network card ip information of ifconfig according to the input paragraph data'''
def parseIfconfig(parsed_data):
    dec = {}
    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

''' Analyze the specified parameters according to the input dmi paragraph data'''
def parseDmi(parsed_data):
    dec = {}
    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

''' Get the Linux system host name'''
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}

''' Get the version information of the Linux system'''
def getOsVersion():
    with open('/etc/issue') as fd:
        for line in fd:
            osver = line.strip()
            break
    return {'osver':osver}

''' Get the model of the CPU and the number of cores of the 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}

''' Get the total physical memory of the Linux system'''
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__':
    dec = {}
    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)

    ''' All the data information obtained will be aligned and displayed in a simple format'''
    for k,v in dic.items():
        print '%-10s:%s' % (k, v)

Experimental test results:
product   :VMware Virtual Platform
osver     :CentOS release 6.4 (Final)
sn        :VMware-56 4d b4 6c 05 e5 20 dc-c6 49 0c e1 e0 18 1c 75
Memory    :1870 MB
cpu_num   :2
ip        :192.168.0.8
vender    :VMware, Inc.
hostname  :vip
cpu_model :Intel(R) i7-4710MQ 2.50GHz

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326469218&siteId=291194637
Recommended