Python: how to check if an FTP server is online

Python: how to check if an FTP server is online

In this article we will see how to check if an FTP server is online with Python.

In this article we will see how to check if an FTP server is online with Python.

We can implement the following function:


import ftplib

def check_if_ftp_host_is_up(host, timeout=5):
     try:
         ftp = ftplib.FTP(host, timeout=timeout)
         ftp.login()
         ftp.quit()
         return True
     except ftplib.all_errors:
         return False

The first line of code import ftplib imports the ftplib module, which provides functionality for communicating with FTP servers.

The check_if_ftp_host_is_up takes two arguments: host and timeout (set to 5 seconds by default). The host argument is the address of the FTP server you want to check.

Within the function, a try-except block is used to handle any exceptions that might occur while connecting to the FTP server.

Within the try block, the function creates an instance of the ftplib.FTP class passing the host address and the specified timeout. This creates an FTP object to communicate with the FTP server.

Next, the login() method of the FTP object is called, which attempts to login to the FTP server. If the attempt is successful, it means that the server is reachable and running.

Immediately after trying to log in, the quit() method is called to close the connection with the FTP server.

Finally, True is returned to indicate that the FTP server is reachable and running.

If an exception of type ftplib.all_errors occurs, the except block is executed. In this case, False is returned to indicate that the FTP server is unreachable or not working.