Reputation: 615
I have a python script in my check_mk installation to send E-Mails and SMS for virtual hosts and services in critical cases. I want to ensure that not more than 15 SMS/E-Mails will be sent in an hour to avoid spam if a physical server was unreachable or down, so that a notification wont be sent for each VM and service. Is there a way of doing that without a counter file? Maybe a running server?
I would do something like this:
import urllib
import urllib2
from os import environ
# parameters
hosts = ['192.168.1.10', '192.168.1.11']
login = 'user'
password = 'secret'
number = 'xxxxxxxxxxxx'
def message():
if environ['NOTIFY_WHAT'] == 'HOST':
msg = "%s %s: %s (%s)" % (
environ['NOTIFY_NOTIFICATIONTYPE'],
environ['NOTIFY_HOSTNAME'],
environ['NOTIFY_HOSTOUTPUT'],
environ['NOTIFY_SHORTDATETIME'])
elif environ['NOTIFY_WHAT'] == 'SERVICE':
msg = "%s %s: %s %s (%s)" % (
environ['NOTIFY_NOTIFICATIONTYPE'],
environ['NOTIFY_HOSTNAME'],
environ['NOTIFY_SERVICEDESC'],
environ['NOTIFY_SERVICEOUTPUT'],
environ['NOTIFY_SHORTDATETIME'])
else:
msg = "Unknown: " + environ['NOTIFY_WHAT']
return msg
def sendSMS(receiver, message):
args = {'login': login, 'pass': password, 'to': receiver, 'message': message}
enc_args = urllib.urlencode(args)
sent = False
error = ''
for host in hosts:
url = 'http://%s/index.php/http_api/send_sms?%s' % (host, enc_args)
if not sent:
try:
result = urllib2.urlopen(url).read()
except urllib2.HTTPError, e:
print('sending sms via host %s failed: %s' % (host, str(e.code)))
except urllib2.URLError, e:
print('sending sms via host %s failed: %s' % (host, str(e.args)))
else:
if result.startswith('OK;'):
sent = True
print('SMS successfully sent via %s to %s.' % (host, receiver))
break
else:
sent = False
print 'Sending SMS via host %s failed: %s' % (host, result.rstrip()))
return
message = message()
sendSMS(number, message)
The script is read and executed by check_mk, it is controlled via WATO. So I have no power over the execution.
Many Thanks
Upvotes: 0
Views: 280
Reputation: 167
You will need to be able to keep the count of how many sms has been sent within a given period of time. You could move your sendSMS function into a simple web service which your script just posts to. That way it can keep track of the rate that sendSMS is being called and act accordingly.
Another way would be to use redis as a place to store your count rather than a file.
Upvotes: 1