Here is a clumsy script to check on an FTP Service on a remote server if running or down. The script is written in Python and is a very draft one, but does the job.
The main goal is to check whether we get any response from the FTP server while we try to connect anonymously. Don’t forget that this script probably won’t work if the FTP server allows anonymous connections.
We simply use the ftplib module to establish the FTP connection. After the successful (or failed) connection, we can report the status of the server via email, to achieve this we use the smtplib module.
The first lines seem simple,
#!/usr/bin/python import ftplib, smtplib server_ip='10.20.30.40' email@example.com' receivers=['firstname.lastname@example.org','email@example.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!