天天看點

通過python擷取伺服器所有資訊

#coding:utf-8

#!/bin/python

#author:rolin

"""

getPubIp(),getPrivateIp(),getSystem_info()"包含系統版本,核心版本",getSsh_version(),getCpu(),getMemory(),getDiskTotal()

注意:url是自己寫的一個接口來擷取雲主機的公網ip,其實很簡單,就是用django寫一個擷取用戶端通路ip,然後把值傳回即可

from subprocess import PIPE,Popen 

import re,urllib,urllib2,platform

from multiprocessing import cpu_count

from collections import namedtuple

import json,os

group = u"換皮"

env = u"遊戲服"

url = "http://192.168.5.6:8000/pubApi/api/getIpAddr/"

def getPubIp():

    """

    擷取公有Ip

    req = urllib2.Request(url)

    response = urllib2.urlopen(req)

    return json.loads(response.read()) 

def getPrivateIp():

    擷取私有Ip

    P = Popen(['ifconfig'],stdout=PIPE)

    data = P.stdout.read()

    list = []

    str = ''

    option = False

    lines = data.split('\n')

    for line in lines:

      if not line.startswith(' '):

        list.append(str)

        str = line

      else:

        str += line

    while True:

      if '' in list:

        list.remove('')

        break

    r_devname = re.compile('(eth\d*|lo)')

    r_mac = re.compile('HWaddr\s([A-F0-9:]{17})')

    r_ip = re.compile('addr:([\d.]{7,15})')

    for line in list:

      devname = r_devname.findall(line)

      mac = r_mac.findall(line)

      ip = r_ip.findall(line)

      if mac:

        return  ip[0]

def getSystem_info():

    擷取系統版本(system_version,kernel_version)

    pd ={} 

    version = platform.dist() 

    os_name = platform.node() 

    os_release = platform.release() 

    os_version = '%s %s' % (version[0],version[1]) 

    pd['os_name'] = os_name 

    pd['os_release'] = os_release 

    pd['os_version'] = os_version 

    return pd

def getSsh_version():

    擷取ssh版本号

    pass

def getCpu():

    擷取cpu個數

    """   

    return cpu_count()

def getMemory():

    擷取伺服器記憶體大小

    meminfo = {}

    with open('/proc/meminfo') as f:

        for line in f:

            meminfo[line.split(':')[0]] = line.split(':')[1].strip()

        totalMem =  int(meminfo['MemTotal'].split(' ')[0])/1048576 + 1

    return str(totalMem)+ 'G'

disk_ntuple = namedtuple('partition',  'device mountpoint fstype')

usage_ntuple = namedtuple('usage',  'total used free percent')

#擷取目前作業系統下所有磁盤  

def disk_partitions(all=False):

    """Return all mountd partitions as a nameduple. 

    If all == False return phyisical partitions only. 

    phydevs = []

    f = open("/proc/filesystems", "r")

    for line in f:

        if not line.startswith("nodev"):

            phydevs.append(line.strip())

    retlist = []

    f = open('/etc/mtab', "r")

        if not all and line.startswith('none'):

            continue

        fields = line.split()

        device = fields[0]

        mountpoint = fields[1]

        fstype = fields[2]

        if not all and fstype not in phydevs:

        if device == 'none':

            device = ''

        ntuple = disk_ntuple(device, mountpoint, fstype)

        retlist.append(ntuple)

    return retlist

#統計某磁盤使用情況,傳回對象  

def disk_usage(path):

    """Return disk usage associated with path."""

    st = os.statvfs(path)

    free = (st.f_bavail * st.f_frsize)

    total = (st.f_blocks * st.f_frsize)

    used = (st.f_blocks - st.f_bfree) * st.f_frsize

    try:

        percent = ret = (float(used) / total) * 100

    except ZeroDivisionError:

        percent = 0

    return usage_ntuple(total, used, free, round(percent, 1))

def getPath():

    擷取磁盤的分區

    disklist = []

    list = disk_partitions()

    for i in list:

        disklist.append(i[1])

    return disklist

def getDiskTotal():

    擷取磁盤總的大小

    newpathlist = []

    pathlist = []

    pathlist = getPath()

    pathlist.append("/dev/shm/")

    totalDiskList = []

    sum = 0

    for path in pathlist:

        disktotal = disk_usage(path)[0] / 1073741824 + 1

        totalDiskList.append(disktotal)

    for count in totalDiskList:

        sum += count

    sum = str(sum) + 'G'

    return sum

print getPubIp(),getPrivateIp(),getSystem_info(),getSsh_version(),getCpu(),getMemory(),getDiskTotal()

本文轉自 luoguo 51CTO部落格,原文連結:http://blog.51cto.com/luoguoling/1876597