#!/usr/bin/python import ftplib, smtplib server_ip='10.20.30.40' sender='sender@email.com' receivers=['john@email.com','doe@email.com']
Above, after importing our modules, we’ve defined the ip address of our FTP server. After that, the sender email address is defined, and then a list containing the receivers. Now we can define our messages. We’ll have two messages, one for the UP status, and one for the DOWN.
message_up=""" From: FTP Status DAEMON To: John , Doe Subject: FTP Service Running The FTP Service on %s is running. """ % server_ip message_down=""" From: FTP Status DAEMON To: John , Doe Subject: FTP Service DOWN! The FTP Service on %s is DOWN!!! """ % server_ip
Now we can actually start the checking. The first try clause is checking if we can establish any kind of connection with the server. If the server is somehow down, or if only the FTP service is shut down, this will return some sort of error, which we will catch with the except clause, handle it with our smtp commands, then raise a system exit.
try : ftp=ftplib.FTP(server_ip) except : print "FTP DOWN !!!" smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender,receivers,message_down) raise SystemExit
And here’s the second check, if we somehow get to this line, it means that we’ve passed the system exit above, so our connection attempt with the server worked, but we’re not sure if the FTP service is actually running without a login attempt. When we try to login, and if anonymous connection isn’t allowed, we’ll get a permission error, handling it with an exception we can email the recievers that the server is running.
try : ftp.login() except ftplib.error_perm : print "FTP Up, Permission Denied." smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender,receivers,message_up)
Now simply connect the dots and add the whole script to your crontab, then you’re good to go!