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

相关文章
|
1月前
|
存储 算法 API
【01】整体试验思路,如何在有UID的情况下获得用户手机号信息,python开发之理论研究试验,如何通过抖音视频下方的用户的UID获得抖音用户的手机号-本系列文章仅供学习研究-禁止用于任何商业用途-仅供学习交流-优雅草卓伊凡
【01】整体试验思路,如何在有UID的情况下获得用户手机号信息,python开发之理论研究试验,如何通过抖音视频下方的用户的UID获得抖音用户的手机号-本系列文章仅供学习研究-禁止用于任何商业用途-仅供学习交流-优雅草卓伊凡
168 82
|
8天前
|
Docker Python 容器
Docker——阿里云服务器使用Docker部署python项目全程小记
本文记录了我在阿里云服务器上使用Docker部署python项目(flask为例)的全过程,在这里记录和分享一下,希望可以给大家提供一些参考。
|
3月前
|
JavaScript API C#
【Azure Developer】Python代码调用Graph API将外部用户添加到组,结果无效,也无错误信息
根据Graph API文档,在单个请求中将多个成员添加到组时,Python代码示例中的`members@odata.bind`被错误写为`members@odata_bind`,导致用户未成功添加。
62 10
|
3月前
|
弹性计算 安全 开发工具
灵码评测-阿里云提供的ECS python3 sdk做安全组管理
批量变更阿里云ECS安全组策略(批量变更)
|
4月前
|
缓存 监控 Linux
Python 实时获取Linux服务器信息
Python 实时获取Linux服务器信息
|
4月前
|
存储 数据采集 数据库
用 Python 爬取淘宝商品价格信息时需要注意什么?
使用 Python 爬取淘宝商品价格信息时,需注意法律和道德规范,遵守法律法规和平台规定,避免非法用途。技术上,可选择 Selenium 和 Requests 库,处理反爬措施如 IP 限制、验证码识别和请求频率控制。解析页面数据时,确定数据位置并清洗格式。数据存储可选择 CSV、Excel、JSON 或数据库,定期更新并去重。还需进行错误处理和日志记录,确保爬虫稳定运行。
|
4月前
|
数据采集 Web App开发 iOS开发
如何利用 Python 的爬虫技术获取淘宝天猫商品的价格信息?
本文介绍了使用 Python 爬虫技术获取淘宝天猫商品价格信息的两种方法。方法一使用 Selenium 模拟浏览器操作,通过定位页面元素获取价格;方法二使用 Requests 和正则表达式直接请求页面内容并提取价格。每种方法都有详细步骤和代码示例,但需注意反爬措施和法律法规。
|
4月前
|
存储 关系型数据库 MySQL
查询服务器CPU、内存、磁盘、网络IO、队列、数据库占用空间等等信息
查询服务器CPU、内存、磁盘、网络IO、队列、数据库占用空间等等信息
1765 2
|
10月前
|
开发者 索引 Python
实践:如何使用python在网页的表格里抓取信息
实践:如何使用python在网页的表格里抓取信息
144 0
|
SQL 关系型数据库 数据库连接
使用python3抓取pinpoint应用信息入库
使用python3通过pinpoint api来获取pinpoint中应用基础信息、上下游链路,并入库
2008 0

热门文章

最新文章