通過python指令碼擷取伺服器硬體資訊

來源:互聯網
上載者:User

標籤:9.1   items   tde   ase   body   roc   製造商   pytho   span   

#!/usr/bin/python# coding:utf-8"""採集機器自身資訊1 主機名稱2 記憶體3 ip與mac地址4 cpu資訊5 硬碟分區資訊6 製造商資訊7 出廠日期8 系統版本"""import socketimport psutilimport subprocessimport timeimport platformimport jsonimport requestsdevice_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 / 1024def 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 retdef 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 retdef 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 dataif __name__ == "__main__":    run()

 

通過python指令碼擷取伺服器硬體資訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.