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

相关文章
|
13天前
|
安全 Java 数据处理
Python网络编程基础(Socket编程)多线程/多进程服务器编程
【4月更文挑战第11天】在网络编程中,随着客户端数量的增加,服务器的处理能力成为了一个重要的考量因素。为了处理多个客户端的并发请求,我们通常需要采用多线程或多进程的方式。在本章中,我们将探讨多线程/多进程服务器编程的概念,并通过一个多线程服务器的示例来演示其实现。
|
1月前
|
数据挖掘 数据安全/隐私保护 开发者
使用Spire.PDF for Python插件从PDF文件提取文字和图片信息
使用Spire.PDF for Python插件从PDF文件提取文字和图片信息
72 0
|
12天前
|
开发者 索引 Python
实践:如何使用python在网页的表格里抓取信息
实践:如何使用python在网页的表格里抓取信息
|
12天前
|
机器学习/深度学习 数据可视化 数据挖掘
用Python进行健康数据分析:挖掘医疗统计中的信息
【4月更文挑战第12天】Python在医疗健康数据分析中扮演重要角色,具备数据处理、机器学习、可视化及丰富生态的优势。基本流程包括数据获取、预处理、探索、模型选择与训练、评估优化及结果可视化。应用案例包括疾病预测、药物效果分析和医疗资源优化,例如使用RandomForestClassifier进行疾病预测,Logit模型分析药物效果,以及linprog优化医疗资源配置。
|
15天前
|
Linux
centos 查看服务器信息 版本cpu
centos 查看服务器信息 版本cpu
12 0
|
16天前
|
Python
Python网络编程基础(Socket编程)UDP服务器编程
【4月更文挑战第8天】Python UDP服务器编程使用socket库创建UDP套接字,绑定到特定地址(如localhost:8000),通过`recvfrom`接收客户端数据报,显示数据长度、地址和内容。无连接的UDP协议使得服务器无法主动发送数据,通常需应用层实现请求-响应机制。当完成时,用`close`关闭套接字。
|
1月前
|
Linux Docker Python
如何将本地的python项目部署到linux服务器中
如何将本地的python项目部署到linux服务器中
91 1
|
1月前
|
存储 数据挖掘 Windows
服务器数据恢复—异常断电导致raid信息丢失的数据恢复案例
由于机房多次断电导致一台服务器中raid阵列信息丢失。该阵列中存放的是文档,上层安装的是Windows server操作系统,没有配置ups。 因为服务器异常断电重启后,raid阵列可以正常使用,所以未引起管理员的注意。后续出现的多次异常断电导致raid报错,服务器无法找到存储设备,进入raid管理模块进行任何操作都会导致操作系统死机。管理员尝试多次重启服务器,故障依旧。
|
1月前
|
数据采集 存储 自然语言处理
使用Python分析网易云歌曲评论信息并可视化处理
在数字化时代,音乐与我们的生活紧密相连,而网易云音乐作为国内知名的音乐平台,拥有庞大的用户群体和丰富的歌曲评论信息。这些评论信息不仅反映了用户对于歌曲的情感态度,还蕴含着大量的有价值的数据。通过对这些评论信息进行分析和可视化处理,我们可以更好地理解用户的喜好、情感变化以及歌曲的影响力。
39 0
|
1月前
|
监控 安全 API
怎么用Python找回微信撤回信息
怎么用Python找回微信撤回信息
33 0