爬虫代理IP由芝麻HTTP服务供应商提供

使用 python 代码收集主机的系统信息,主要:主机名称、IP、系统版本、服务器厂商、型号、序列号、CPU信息、内存等系统信息。

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

'''
收集主机的信息:
主机名称、IP、系统版本、服务器厂商、型号、序列号、CPU信息、内存信息
'''

from subprocess import Popen, PIPE
import 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 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 

使用Python收集获取Linux系统主机信息的更多相关文章

  1. 使用 python 收集获取 Linux 系统主机信息

    使用 python 代码收集主机的系统信息,主要:主机名称.IP.系统版本.服务器厂商.型号.序列号.CPU信息.内存等系统信息. #!/usr/bin/env python #encoding: u ...

  2. 用Python获取Linux资源信息的三种方法

    方法一:psutil模块 #!usr/bin/env python # -*- coding: utf-8 -*- import socket import psutil class NodeReso ...

  3. Python 通过dmidecode获取Linux服务器硬件信息

    通过 dmidecode 命令可以获取到 Linux 系统的包括 BIOS. CPU.内存等系统的硬件信息,这里使用 python 代码来通过调用 dmidecode 命令来获取 Linux 必要的系 ...

  4. Python 实现获取微信好友信息

    最近用闲余时间看了点python,在网上冲浪时发现有不少获取微信好友信息的博客,对此比较感兴趣,于是自己敲了敲顺便记录下来. 一.使用 wxpy 模块库获取好友男比例信息和城市分布. # -*- co ...

  5. python flask获取微信用户信息报404,nginx问题

    在学习flask与微信公众号时问题,发现测试自动回复/wechat8008时正常,而测试获取微信用户信息/wechat8008/index时出现404.查询资料后收发是nginx配置问题. 在loca ...

  6. Python知识点 - 获取当前系统主机名、用户名、用户目录。

    代码示例: import socket, getpass, os # 获取当前系统主机名 host_name = socket.gethostname() # 获取当前系统用户名 user_name ...

  7. python flask获取微信用户信息流程

    需要了解的几个url 用户第一次访问时的url,包含以下几个参数 https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID& ...

  8. Python之获取微信好友信息

    save_info.py: #!/usr/bin/python # -*- coding: UTF-8 -*- import itchat import pickle itchat.auto_logi ...

  9. Python脚本获取Linux系统信息

    # -*- coding:utf-8 -*- import os import subprocess import re import hashlib #对字典取子集 def sub_dict(for ...

随机推荐

  1. ABP官方文档翻译 2.3 缓存

    缓存 介绍 ICacheManager 警告:GetCache方法 ICache ITypedCache 配置 实体缓存 实体缓存如何工作 Redis缓存集成 介绍 ABP为缓存提供了一个抽象接口,它 ...

  2. Using Custom Domains With IIS Express In Asp.Net Core

    IIS Express是一个Mini版的IIS,能够支持所有的Web开发任务,但是这种设计有一些缺陷,例如只能通过localhost:<port>的方式来访问我们的应用程序,看起来就有点不 ...

  3. 用 label 控制 Pod 的位置 - 每天5分钟玩转 Docker 容器技术(128)

    默认配置下,Scheduler 会将 Pod 调度到所有可用的 Node.不过有些情况我们希望将 Pod 部署到指定的 Node,比如将有大量磁盘 I/O 的 Pod 部署到配置了 SSD 的 Nod ...

  4. S5PV210中断处理

    _start: 1.设置栈空间:防止之前的UBOOT代码被覆盖,应为c中需要栈空间 ldr sp, =0x40010000 2.设置CPSR的I,F位,A8打开IRQ,FIQ中断: mov r0, # ...

  5. nginx的location优先级

    在nginx配置文件中,location主要有这几种形式: 1. 正则匹配 location ~ /abc { } 2. 不区分大小写的正则匹配 location ~* /abc { } 3. 匹配路 ...

  6. 分布式集群下的Session存储方式窥探

    传统的应用服务器,自身实现的session管理是大多是基于单机的,对于大型分布式网站来说,支撑其业务的远远不止一台服务器,而是一个分布式集群,请求在不同的服务器之间跳转.那么,如何保持服务器之前的se ...

  7. 前端开发利器webStorm

    这里推荐一个前端开发工具webStorm.用了大概快半年了,发现所有其他工具无出其右的.目前最新版本已经到4.0.2,半年前还是2.X 相比aptana.dreamweaver.sublime和vim ...

  8. 拥抱.NET Core系列:MemoryCache 初识

    Cache是一个绝大多数项目会用到的一个技术,说起到缓存可能就联想到 Set.Add.Get.Remove.Clear 这几个方法.那么在.NET Core中微软给我们带来了什么样的缓存体验呢?今天我 ...

  9. 2017年StackOverflow上最好的20个Python问题

    1.Python的 .. (点号 点号) 是什么语法? 答案地址:https://stackoverflow.com/questions/43487811/what-is-python-dot-dot ...

  10. Yii2按需加载图片怎么做?

    按需加载图片应该用 jQuery LazyLoad 图片延迟加载按需加载文件夹应该用 Yii::import