zoukankan      html  css  js  c++  java
  • 通过python脚本获取服务器硬件信息

    #!/usr/bin/python
    # coding:utf-8
    
    """
    采集机器自身信息
    1 主机名
    2 内存
    3 ip与mac地址
    4 cpu信息
    5 硬盘分区信息
    6 制造商信息
    7 出厂日期
    8 系统版本
    """
    import socket
    import psutil
    import subprocess
    import time
    import platform
    import json
    import requests
    
    device_white = ['eth1', 'eth2', 'eth3', 'bond0', 'bond1']
    
    
    def get_hostname():
        return socket.gethostname()
    
    
    def get_meminfo():
        with open("/proc/meminfo") as f:
            tmp = int(f.readline().split()[1])
            return tmp / 1024
    
    
    def get_device_info():
        ret = []
        for device, device_info in psutil.net_if_addrs().iteritems():
            if device in device_white:
                tmp_device = {}
                for sinc in device_info:
                    if sinc.family == 2:
                        tmp_device['ip'] = sinc.address
                    if sinc.family == 17:
                        tmp_device['mac'] = sinc.address
                ret.append(tmp_device)
        return ret
    
    def get_cpu_info():
        ret = {'cpu':'','num':0}
        with open('/proc/cpuinfo') as f:
            for line in f:
                tmp = line.split(":")
                key = tmp[0].strip()
                if key == "processor":
                    ret['num'] += 1
                if key == "model name":
                    ret['cpu'] = tmp[1].strip()
        return ret
    
    def get_disk_info():
        cmd = """/sbin/fdisk -l|grep Disk|egrep -v 'identifier|mapper|Disk label'"""
        disk_data = subprocess.Popen(cmd, shell=True, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
        patition_size = []
        for dev in disk_data.stdout.readlines():
            # size = int(dev.strip().split()[4]) / 1024 / 1024/ 1024
            size = int(dev.strip().split(',')[1].split()[0]) / 1024 / 1024/ 1024
            patition_size.append(str(size))
        return " + ".join(patition_size)
    
    # 获取制造商信息
    def get_manufacturer_info():
        ret = {}
        cmd = """/usr/sbin/dmidecode | grep -A6 'System Information'"""
        manufacturer_data = subprocess.Popen(cmd, shell = True, stdout = subprocess.PIPE, stderr=subprocess.STDOUT)
    
        for line in manufacturer_data.stdout.readlines():
            if 'Manufacturer' in line:
                ret['manufacturers'] = line.split(':')[1].strip()
            elif 'Product Name' in line:
                ret['server_type'] = line.split(':')[1].strip()
            elif 'Serial Number' in line:
                ret['st'] = line.split(':')[1].strip()
            elif 'UUID' in line:
                ret['uuid'] = line.split(':')[1].strip()
        return ret
    
    # 获取出厂日期
    def get_real_date():
        cmd = """/usr/sbin/dmidecode | grep -i release"""
        date_data = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        real_date = date_data.stdout.readline().split(':')[1].strip()
        return time.strftime('%Y-%m-%d', time.strptime(real_date, "%m/%d/%Y"))
    
    def get_os_version():
        return ' '.join(platform.linux_distribution())
    
    def get_innerip(ipinfo):
        inner_device = ['eth1', 'bond0']
        ret = {}
        for info in ipinfo:
            if info.has_key('ip') and info.get('device', None) in inner_device:
                ret['ip'] = info.get('ip')
                ret['mac_address'] = info.get('mac')
                return ret
        return {}
    
    def run():
        data = {}
        data['hostname'] = get_hostname()
        device_info = get_device_info()
        data.update(get_innerip(device_info))
        data['ipinfo'] = json.dumps(device_info)
    
        cpu_info = get_cpu_info()
        data['server_cpu'] = "{cpu} {num}".format(**cpu_info)
        data['server_disk'] = get_disk_info()
        data['server_mem'] = get_meminfo()
        data.update(get_manufacturer_info())
        data['manufacture_date'] = get_real_date()
        data['os'] = get_os_version()
        if 'virtualbox' == data['server_type']:
            data['vm_status'] = 0
        else:
            data['vm_status'] = 1
        # return data
        send(data)
    
    def send(data):
        url = "http://192.168.99.10:8000/resources/server/reporting/"
        r = requests.post(url, data = data)
        print r
        print data
    
    if __name__ == "__main__":
        run()

    # 使用函数式编程获取内存使用信息,写入html文件中

    #coding:utf-8
    
    # 使用函数式编程获取内存使用信息,写入html文件中
    
    # 将内存占用的数字带上单位
    def num_format(num):
        num = int(num)
        o = 'KB'
        if num > 1024*1024:
            num /= 1024*1024.0
            o = 'GB'
            return '%2f%s' % (num ,o)
        elif num > 1024:
            num /= 1024.0
            o = 'MB'
            return '%2f%s' % (num, o)
        
        return '%2f%s' % (num, o)
    
    # 获取内存的数字
    def get_mem(arr):
        tmp = arr.split()
        tmp[1] = num_format(tmp[1])
        # print 'tmp = %s' % tmp[:2]
        return tmp[:2]
    
    # 读取meminfo的信息
    def operate(key):
        with open('/proc/meminfo') as f:
            mem_total = key(f.readline())
            mem_free = key(f.readline())
            mem_ava = key(f.readline())
            mem_buff = key(f.readline())
            mem_cached = key(f.readline())
            return [mem_total,mem_free,mem_ava,mem_buff,mem_cached]
    
    # 将信息写入html页面
    def genarate_html(rst_list):
        str_html = '<table border="1" cellpading=0 cellspacing=0>'
        str_html += '<tr><th>项目</th><th>占用内存</th></tr>'
        for mem in rst_list:
            str_html += '<tr><td>%s</td><td>%s</td></tr>' % tuple(mem)
            print mem
        str_html += '</table>'
    
        with open('mem.html', 'w') as f:
            f.write(str_html)
    
    def main():
        rst_list = operate(get_mem)
        genarate_html(rst_list)
    
    
    if __name__ == "__main__":
        main()
  • 相关阅读:
    Android中Context具体解释 ---- 你所不知道的Context
    JDK6、Oracle11g、Weblogic10 For Linux64Bit安装部署说明
    matplotlib 可视化 —— 定制 matplotlib
    matplotlib 可视化 —— 移动坐标轴(中心位置)
    matplotlib 可视化 —— 移动坐标轴(中心位置)
    matplotlib 可视化 —— 定制画布风格 Customizing plots with style sheets(plt.style)
    matplotlib 可视化 —— 定制画布风格 Customizing plots with style sheets(plt.style)
    指数函数的研究
    指数函数的研究
    指数分布的研究
  • 原文地址:https://www.cnblogs.com/reblue520/p/8078503.html
Copyright © 2011-2022 走看看