Get all server information via Python

Source: Internet
Author: User
Tags disk usage server memory

#coding: Utf-8
#!/bin/python
#author: Rolin
"""

Getpubip (), Getprivateip (), Getsystem_info () "contains system version, kernel version", Getssh_version (), Getcpu (), GetMemory (), Getdisktotal ()

Note: The URL is to write an interface to get the cloud host public IP, in fact, is very simple, is to use Django write a Get client access IP, and then return the value can be

"""
From subprocess Import Pipe,popen
Import Re,urllib,urllib2,platform
From multiprocessing import Cpu_count
From collections Import Namedtuple
Import Json,os
Group = U "Skin-changing"
env = u "Game Suit"
url = "http://192.168.5.6:8000/pubApi/api/getIpAddr/"

Def GETPUBIP ():
"""
Get public IP
"""
req = Urllib2. Request (URL)
Response = Urllib2.urlopen (req)
Return Json.loads (Response.read ())
Def GETPRIVATEIP ():
"""
Get Private 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 ():
"""
Get System version (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 ():
"""
Get the SSH version number
"""
Pass

Def getcpu ():
"""
Get the number of CPUs
"""
Return Cpu_count ()

Def getmemory ():
"""
Get Server memory Size
"""
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
#统计某磁盘使用情况, returns the object
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 ():
"""
Get Partition of Disk
"""
Disklist = []
List = Disk_partitions ()
For I in list:
Disklist.append (I[1])
Return disklist
Def getdisktotal ():
"""
Get the total size of the disk
"""
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 ()


This article is from the "Automation Rolin" blog, so be sure to keep this source http://luoguoling.blog.51cto.com/1568501/1876597

Get all server information via Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.