Reputation: 133
I was wondering if there is an easy way of knowing whether a connection to an FTP server is still active using ftplib.
So if you have an active connection like this:
import ftplib
ftp = ftplib.FTP("ftp.myserver.com", "admin", "pass123")
is there something like the following pseudo code that can be queried to check if the connection is still active?
if ftp.is_connected() == True:
print "Connection still active"
else:
print "Disconnected"
Upvotes: 2
Views: 1910
Reputation: 1233
You could try retrieving something from the server, and catching any exceptions and returning whether or not it's connected based on that.
For example:
def is_connected(ftp_conn):
try:
ftp_conn.retrlines('LIST')
except (socket.timeout, OSError):
return False
return True
This simple example will print the 'LIST' results to stdout, you can change that by putting your own callback into the retrlines method
(Make sure you set a timeout in the initial FTP object construction, as the default is for it to be None.)
ftp = ftplib.FTP("ftp.gnu.org", timeout=5, user='anonymous', passwd='')
Upvotes: 3