通过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()
    



本文转自 luoguo 51CTO博客,原文链接:http://blog.51cto.com/luoguoling/1876597

上一篇:【Java 并发编程】线程池机制 ( 线程池执行任务细节分析 | 线程池执行 execute 源码分析 | 先创建核心线程 | 再放入阻塞队列 | 最后创建非核心线程 )


下一篇:Java线程池类ThreadPoolExecutor、ScheduledThreadPoolExecutor及Executors工厂类