1. 程式人生 > >服務器硬件信息采集python版本

服務器硬件信息采集python版本

logic root [1] script HA 硬件 odin percent error

#!/usr/bin/python
#coding:utf-8

‘‘‘
# -------------------------------------------------------------------------------
# Filename: hardwareinfo.py
# Revision: 0.1
# Date: 2018/04/03
# Author: stivee
# Email: [email protected]
# Description: 服務器,python2.7
# Notes: 啟動:nohup python hardwareinfo.py > /dev/null 2>&1 &
# -------------------------------------------------------------------------------
‘‘‘

#先下載psutil庫:pip install psutil
import psutil
import sys,os,datetime,time,subprocess,re,json,shutil

try:
import psutil
except ImportError as e:
with open(‘/home/logs/hardwareinfoerror.log‘,‘a‘) as fe:
fe.write(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + repr(e) + ‘\n‘)
sys.exit()

totalinfo = {}

def getLoad():
k = 1.0
loadavg = {}
if os.path.exists(‘/proc/loadavg‘):
load = [float(open(‘/proc/loadavg‘).read().split()[x]) * k for x in range(3)]
else:
tokens = subprocess.check_output([‘uptime‘]).split()
load = [float(str(x).strip(‘[b,\‘,]‘)) * k for x in tokens[-3:]]
loadavg[‘loadavg‘] = load
return loadavg

def getMem():
mem = {}
allinfo = psutil.virtual_memory()
percent = (‘%.3f‘%(float(allinfo.used)/float(allinfo.total)))
total = allinfo.total
used = allinfo.used
free = allinfo.free
mem[‘mem_percent‘] = percent
mem[‘mem_total‘] = total
mem[‘mem_used‘] = used
mem[‘mem_free‘] = free
return mem

def getUsers():
alluserinfo = {}
allusers = psutil.users()
userscount = len(allusers)
userinfo = []
for i in allusers:
userinfo.append(i.name + "-" + i.host + "-" + time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(int(‘%d‘%i.started))))
userinfo = ‘ ‘.join(userinfo)
uptime = subprocess.check_output([‘uptime‘]).split()
uptime = str(uptime[2]).strip(‘[b,\‘,]‘) + ‘ days ‘ + str(uptime[4]).strip(‘[b,\‘,]‘)
pidsnum = len(psutil.pids())
alluserinfo[‘userinfo‘] = userinfo
alluserinfo[‘uptime‘] = uptime
alluserinfo[‘pidsnum‘] = pidsnum
return alluserinfo

def getCpu():
cpuinfo = {}
cpucount = psutil.cpu_count(logical=False)
cpuused = psutil.cpu_percent()
cpuinfo[‘cpucount‘] = cpucount
cpuinfo[‘cpuused‘] = cpuused
return cpuinfo

def getDisk():
diskinfo = {}
diskroot = psutil.disk_usage(‘/‘).percent
diskhome = psutil.disk_usage(‘/home/‘).percent
diskinfo[‘diskroot‘] = diskroot
diskinfo[‘diskhome‘] = diskhome
return diskinfo

def getNet():
netlist = [x for x in psutil.net_io_counters(pernic=True).keys() if re.search(‘^e‘,x)]
netflow = {}
netflow_in = {}
netflow_out = {}
ut = {}
recv = []
sent = []
for net in netlist:
recv.append(psutil.net_io_counters(pernic=True).get(net).bytes_recv)
sent.append(psutil.net_io_counters(pernic=True).get(net).bytes_sent)
time.sleep(1)
recv.append(psutil.net_io_counters(pernic=True).get(net).bytes_recv)
sent.append(psutil.net_io_counters(pernic=True).get(net).bytes_sent)
netflow_in[net+‘_in‘] = (recv[1] - recv[0]) / 1024 * 8
netflow_out[net+‘_out‘] = (sent[1] - sent[0]) / 1024 * 8
recv = []
sent = []
netflow.update(netflow_in)
netflow.update(netflow_out)
return netflow

try:
if __name__ == "__main__":
while True:
totalinfo[‘loadavg‘] = getLoad()
totalinfo[‘mem‘] = getMem()
totalinfo[‘users‘] = getUsers()
totalinfo[‘cpu‘] = getCpu()
totalinfo[‘disk‘] = getDisk()
totalinfo[‘net‘] = getNet()
filesize = os.path.getsize(‘/home/logs/totalinfo.log‘)
if filesize > 1024000000:
shutil.move(‘/home/logs/totalinfo.log‘,‘/home/logs/totalinfo.logbak‘)
with open(‘/home/logs/totalinfo.log‘,‘a‘) as f:
f.write("::" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + "::" + json.dumps(totalinfo) + ‘\n‘)
time.sleep(5)
except Exception as e:
with open(‘/home/logs/hardwareinfoerror.log‘,‘a‘) as f:
f.write(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + repr(e) + ‘\n‘)
else:
with open(‘/home/logs/hardwareinfostatus.log‘,‘a‘) as f:
f.write(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ‘:OK‘ + ‘\n‘)

服務器硬件信息采集python版本