#!/usr/bin/env python
"""
monitor script
"""
import os, sys, socket, smtplib
from email.mime.text import MIMEText
def checkServer( host, port ):
serverSocket = socket.socket()
serverSocket.settimeout(3)
try:
serverSocket.connect((host, port))
except socket.error:
return 1
hosts={
'gw.domain.com':[ 25, 80, 110, 143, 524, 1677 ],
'www.domain.com':[ 80 ],
'server.domain.com': [ 524 ]
}
content=''
for host in hosts:
for port in hosts[host]:
status=checkServer( host, port )
if status:
content+=' Port %s on %s is down.\n' % ( port, host )
if content:
msg = MIMEText(content)
msg['Subject'] = 'Monitor'
msg['From'] = 'user@domain.com'
msg['To'] = 'xxxxxxxxxx@messaging.sprintpcs.com'
s = smtplib.SMTP('mx.messaging.sprintpcs.com', 25)
s.sendmail('monitor@domain.com', 'xxxxxxxxxx@messaging.sprintpcs.com', msg.as_string())
s.quit()
Wednesday, September 14, 2011
Quick and Dirty Server Monitoring with Python
Sometimes you just need a quick and dirty script for monitoring servers to see if they are up. I wrote the following python script and have it running from cron so that it will notify me via SMS when a server's service isn't responding. The list of hosts is in a python dictionary with the key being the hostname or ip to monitor and the value being a list of service ports to check. If a host/port doesn't respond, it emails to the Sprint messaging service which appears on my phone. Any provider that has an email to SMS gateway should work. It isn't anywhere near a full fledged monitoring system but works well enough.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment