python交换机运维 web监控_Python运维三十六式:用Python写一个简单的监控系统

此Python脚本通过获取CPU负载、内存使用和主机名,每分钟将系统信息以JSON格式发送到51reboot.com:8888。它展示了如何使用`urllib`和`urllib2`库进行HTTP请求,并结合了系统性能指标的获取方法。
摘要由CSDN通过智能技术生成

#!/usr/bin/env python

import inspect

import time

import urllib, urllib2

import json

import socket

class mon:

def __init__(self):

self.data = {}

def getTime(self):

return str(int(time.time()) + 8 * 3600)

def getHost(self):

return socket.gethostname()

def getLoadAvg(self):

with open('/proc/loadavg') as load_open:

a = load_open.read().split()[:3]

return ','.join(a)

def getMemTotal(self):

with open('/proc/meminfo') as mem_open:

a = int(mem_open.readline().split()[1])

return a / 1024

def getMemUsage(self, noBufferCache=True):

if noBufferCache:

with open('/proc/meminfo') as mem_open:

T = int(mem_open.readline().split()[1])

F = int(mem_open.readline().split()[1])

B = int(mem_open.readline().split()[1])

C = int(mem_open.readline().split()[1])

return (T-F-B-C)/1024

else:

with open('/proc/meminfo') as mem_open:

a = int(mem_open.readline().split()[1]) - int(mem_open.readline().split()[1])

return a / 1024

def getMemFree(self, noBufferCache=True):

if noBufferCache:

with open('/proc/meminfo') as mem_open:

T = int(mem_open.readline().split()[1])

F = int(mem_open.readline().split()[1])

B = int(mem_open.readline().split()[1])

C = int(mem_open.readline().split()[1])

return (F+B+C)/1024

else:

with open('/proc/meminfo') as mem_open:

mem_open.readline()

a = int(mem_open.readline().split()[1])

return a / 1024

def runAllGet(self):

#自动获取mon类里的所有getXXX方法,用XXX作为key,getXXX()的返回值作为value,构造字典

for fun in inspect.getmembers(self, predicate=inspect.ismethod):

if fun[0][:3] == 'get':

self.data[fun[0][3:]] = fun[1]()

return self.data

if __name__ == "__main__":

while True:

m = mon()

data = m.runAllGet()

print data

req = urllib2.Request("http://51reboot.com:8888", json.dumps(data), {'Content-Type': 'application/json'})

f = urllib2.urlopen(req)

response = f.read()

print response

f.close()

time.sleep(60)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值