Created
July 4, 2016 21:05
-
-
Save JustinGrote/73b269d1db1b12a6daa83bbef4291c01 to your computer and use it in GitHub Desktop.
SolusVM Monitor Alert
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
###DESCRIPTION | |
#This script sends an email alert when a specific SolusVM metric | |
#exceeds its monitor | |
###USAGE | |
#solusvm_monitor.py <metric> <monitor> | |
#Metric: One of hdd, bw, or mem. Default is bw | |
#Monitor: Threshold to alert when exceeded. Default is 80 | |
#Example CRONTAB entry | |
#5 * * * * /path/to/solusvm_monitor.py bw 85 | |
###IMPORTS | |
import socket | |
import smtplib | |
import requests | |
import email | |
from email.mime.text import MIMEText | |
from email.mime.multipart import MIMEMultipart | |
from lxml import html | |
from sys import argv | |
from os.path import realpath | |
###SETTINGS | |
#URL of your SolusVM Instance | |
API_URL='https://vpscp.ramnode.com' | |
API_PATH='/api/client/command.php' | |
#Key and hash for the API | |
KEY='XXXXX-XXXXX-XXXX' | |
HASH='examplehashaoiawerj2340192lkfjlJSDLIW' | |
#Action to take. Currently only info is supported | |
ACTION='info' | |
#Metric to gather. (hdd, mem, or bw) | |
METRIC='bw' | |
#Threshold over which to alert | |
MONITOR=80 | |
#SMTP Settings | |
HOSTNAME = str(socket.gethostname()) | |
FROM = 'monitoralert@{}'.format(socket.getfqdn()) | |
TO = 'example@gmail.com' | |
SMTPSERVER = 'gmail-smtp-in.l.google.com' | |
SMTPPORT = '25' | |
###MAIN | |
#Override if args are specified | |
if len(argv)==3: | |
METRIC=argv[1] | |
MONITOR=int(argv[2]) | |
print(len(argv)) | |
print(METRIC) | |
print(MONITOR) | |
#Construct the request params | |
requestparams = { | |
'key':KEY, | |
'hash':HASH, | |
'action':ACTION, | |
METRIC:'true' | |
} | |
#Query for the metric and format the result | |
response = requests.get((API_URL + API_PATH), params=requestparams) | |
tree = html.fromstring(response.content) | |
#Find the metric, get the percentused part of the string and convert to # | |
percentused = int(tree.find(METRIC).text.split(',')[3]) | |
#Send a mail notice if the current exceeds the threshold | |
if percentused > MONITOR: | |
MSG = MIMEMultipart() | |
MSG['Subject'] = '{} {} Warning: {}% used'.format(HOSTNAME,METRIC,percentused) | |
MSG['From'] = FROM | |
MSG['To'] = TO | |
BODY = 'Generated by {}'.format(realpath(__file__)) | |
MSG.attach(MIMEText(BODY,'plain')) | |
s = smtplib.SMTP(SMTPSERVER,SMTPPORT) | |
#s.set_debuglevel(1) | |
s.sendmail(FROM, TO, (MSG.as_string())) | |
s.quit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment