#!/usr/bin/env python2
#coding:utf-8
import logging
import os.path
try:
import json
except:
import simplejson as json
import subprocess
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import base64 as b64
import optparse
logging.basicConfig(
format='%(asctime)s - %(pathname)s[%(lineno)d] - %(levelname)s: %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
class RabbitMQMoniter():
def __init__(self, host='', port=15672, username='guest', password='guest', watermark = 10000):
self.host = host
self.port = port
self.username = username
self.password = password
self.watermark = watermark
"""
Notify Emali Configuration.
"""
def send_for_mail(self,messagetext):
with open('mail.ini','r') as f:
data = [ line.strip() for line in f.readlines() ]
sender = data[0]
receivers = data[1]
message = MIMEText(messagetext,'plain', 'utf-8')
message['From'] = Header(data[0].split('@')[0],'utf-8')
message['To'] = Header(receivers, 'utf-8')
subject = '[Alerting-{0}] RabbitMq Vhosts Messsages Alert.'.format(self.host)
message['Subject'] = Header(subject, 'utf-8')
smtpObj = smtplib.SMTP(data[2],port=25)
try:
smtpObj.sendmail(sender, receivers.split(","), message.as_string())
print("Send mail successfully.")
except Exception as err:
print(str(err))
"""
Check RabbitMQ Vhosts API
"""
def check_rabbitmq(self):
mail_msgtext = ""
getallnames = """curl -s -u {0}:{1} http://{2}:{3}/api/vhosts""".format(self.username,self.password,self.host,self.port)
result = subprocess.check_output(getallnames, shell=True)
result = result.decode('utf-8')
outputjson = json.loads(result) # 格式化获取到的信息
count = 1
for msginfo in outputjson:
if (msginfo.__contains__('messages')): # 判断虚拟主机信息中是否有messages字段
if msginfo['messages'] > self.watermark:
msgtext = ('{2}: {0}' + " "*(30 - len(msginfo['name'])) + '{1}').format(msginfo['name'],msginfo['messages'],count) # 有则邮件通知
print(msgtext)
mail_msgtext = mail_msgtext + msgtext + '\n'
count += 1
continue
else:
mail_msgtext = ""
return mail_msgtext
class xor_enc_dec():
def __init__(self,key):
self.key = key
def xor_encrypt(self, tips):
lkey = len(self.key)
secret = []
num = 0
for each in tips:
if num >= lkey:
num = num % lkey
secret.append(chr(ord(each) ^ ord(self.key[num])))
num += 1
return b64.b64encode("".join(secret).encode()).decode()
def xor_decrypt(self, secret):
tips = b64.b64decode(secret.encode()).decode()
lkey = len(self.key)
secret = []
num = 0
for each in tips:
if num >= lkey:
num = num % lkey
secret.append(chr(ord(each) ^ ord(self.key[num])))
num += 1
return "".join(secret)
if __name__ == '__main__':
usage = "Usage: RabbitmqMorAll -i input_file -o output_file.\n RabbitmqMorAll -c output_file."
CommandParser = optparse.OptionParser(usage, version="RabbitmqMorAll 1.0 By zayki.",
add_help_option=False)
CommandParser.add_option("-c", "--config", help="Configuration file's name", action="store")
CommandParser.add_option("-i", "--input", help="Configuration file with not encrypt data.", action="store")
CommandParser.add_option("-o", "--output", help="Configuration file with encrypt data.", action="store")
(args, _) = CommandParser.parse_args()
if args.input is not None and args.output is not None:
try:
enc_func = xor_enc_dec('11211#@123!')
with open(args.input, 'r') as f:
lines = [line.strip() for line in f.readlines()]
if os.path.isfile(args.output):
os.remove(args.output)
with open(args.output,'a') as fo:
for line in lines:
if not line.startswith('#'):
out_line = enc_func.xor_encrypt(line)
fo.write(out_line + '\n')
print("Generate configure file {0} successfully.".format(args.output))
except Exception as err:
print(str(err))
elif args.config is not None:
with open(args.config, 'r') as f:
lines = [line.strip() for line in f.readlines()]
dec_func = xor_enc_dec('11211#@123!')
for line in lines:
if line and not line.startswith('#'):
data = dec_func.xor_decrypt(line)
# print(data)
paras = data.split(',')
obj = RabbitMQMoniter(paras[0], paras[1], paras[2], paras[3], int(paras[4]))
mail_msgtext = obj.check_rabbitmq()
if mail_msgtext != "":
obj.send_for_mail(mail_msgtext)
else:
print("Nothing is unusual for {0}.".format(paras[0]))
else:
CommandParser.print_help()
input_file.ini
10.10.1.2,15672,guest,guest,10000
10.10.1.3,15672,guest,guest,50000
mail.ini
monitor@test.com.cn
receiver1@test.com.cn,receiver2@test.com.cn
email.test.com.cn
使用方法:
# RabbitmqMorAll -i input_file.ini -o output_file.ini
# RabbitmqMorAll -c output_file.ini