通過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('')
      else:
        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")
    for line in f:
        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:
            continue
        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()
    

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章