Мониторинг сайтов и уведомление по почте без установленного почтового сервера

По независящим от нас причинам упал сайт, спустя несколько часов только узнали об этом, поэтому было решено, для “быстрого реагирования”, сделать мониторинг на локальном сервере, одна беда, он в интранете и почтового сервера на нем нет. В результате был сделан несложный скрипт, позволяющий отправлять отчеты о падении с любого доступного вам почтового адреса (gmail.com, mail.ru, yandex.ru). Поддерживается TLS авторизация для SMTP и HTTPS для протокола мониторинга.

Инструкция по эксплуатации:

Usage: site_down_notifier.py -s http://site.com -n [email protected]
Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -s SITE, --site=SITE  define site for monitoring (url like http://site.com/)
  -n EMAILS, --notify=EMAILS
                        emails for notification (comma separated)
  -r STR, --str=STR     phrase for checking on your site page
  -t TLS, --mailtls=TLS
                        use secure email connection (True/1, False/0)
  -m SERVER, --mailserver=SERVER
                        mail server (smtp.gmail.com)
  -p PORT, --mailport=PORT
                        smtp port of mail server (25)
  -w PASSWORD, --mailpass=PASSWORD
                        password for mail server
  -b EMAIL, --mailbox=EMAIL
                        account for mail server

Исходный код скрипта:


#! /usr/bin/python

import smtplib
import httplib
import sys
import re
from optparse import OptionParser
from pprint import pprint

class GMailer:
    
    def __init__(self, server, port, login, password, tls = False):
        if tls:            
            self._server = smtplib.SMTP_SSL(server, port)
        else:
            self._server = smtplib.SMTP(server, port)
            
        self._login = login
        self._server.set_debuglevel(1)        
        self._server.login(login, password)
        
    def send(self, to, subject, message):
        msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s"
               % (self._login, to, subject, message))
        
        return self._server.sendmail(self._login, to, msg) 

    def close(self):
        self._server.quit()

parser = OptionParser(usage = "%prog -s http://site.com -n [email protected]", version="%prog 1.0")
parser.add_option("-s", "--site", dest="site",help="define site for monitoring (url like http://site.com/)", metavar="SITE")
parser.add_option("-n", "--notify", dest="emails", help="emails for notification (comma separated)", metavar="EMAILS")
parser.add_option("-r", "--str", dest="sitestr", help="phrase for checking on your site page", metavar="STR", default = "")
parser.add_option("-t", "--mailtls", dest="tls", help="use secure email connection (True/1, False/0)", metavar="TLS", default=False)
parser.add_option("-m", "--mailserver", dest="mailserver", help="mail server (smtp.gmail.com)", metavar="SERVER")
parser.add_option("-p", "--mailport", dest="mailport", help="smtp port of mail server (25)", metavar="PORT", default=25)
parser.add_option("-w", "--mailpass", dest="mailpass", help="password for mail server", metavar="PASSWORD")
parser.add_option("-b", "--mailbox", dest="mailbox", help="account for mail server", metavar="EMAIL")

(options, args) = parser.parse_args()

if options.site and options.emails and options.mailserver and options.mailpass:
    error = ""
        
    result = re.search("^(http|https)://([\w.-]*)(.*)", options.site)
    
    
    if result.lastindex < 3:
        print("Wrong url: %s" % (options.site))
        exit()
    else:                                    
        try:
            if result.group(1) == "https":
                conn = httplib.HTTPSConnection(result.group(2), timeout=100)
            else:
                conn = httplib.HTTPConnection(result.group(2), timeout=100)
            conn.request("GET", result.group(3))
            r1 = conn.getresponse()    
            
            if(r1.status != 200):
                error = "host unavailable"
            elif (options.sitestr != "") and (r1.read().find(options.sitestr) <= 0):
                error = "wrong content on home"
        except:
            error = "host not found"
            
        if error != "":
            mailer = GMailer(options.mailserver, options.mailport, options.mailbox, options.mailpass, options.tls)
            for email in options.emails.split(","):
                if mailer.send(email, "psycare", error):
                    print("Report to %s sent" % (email))                
            mailer.close()
            print("errors sent")
        else:
            print("everything is ok")
else:
    print "not enough parameters"    

Site Footer

Sliding Sidebar

About Me

About Me

For whom this blog for?

For those who are interested in modern Internet technologies, IT business, startups, management, quality control, personal effectiveness, motivation. Here I write about what is interesting, about problems I faced and solutions I found. I hope it will be interesting to you either.

What motivates me to write?

The desire to improve, to study deeper topics that interest me. Find people with similar problems and tasks, together look for ways out and solutions.

Feel free to contact if you have anything to say to me

Old Flash site with my artistic works and misuc.