Search code examples
pythonpython-3.xftpftplib

How to check whether FTP login is successful or not in Python ftplib?


I am developing a FTP client using Python ftplib. Here is my code:

def connectftp():
ftp=ftplib.FTP('hostname')
print(ftp.getwelcome())
ftp.login(username, password)

I want to display a message saying "Login successful" when the FTP login is successful. How to do that? How to check whether the login is successful or not?


Solution

  • The FTP.login method throws an exception, when an authentication fails, so you can simply do:

    ftp.login(username, password)
    print("Login successful")
    

    If you want to react to authentication failures as well, handle the exception:

    try:
        ftp.login(username, password)
        print("Login successful")
        # do your FTP stuff here
    except:
        print("Login failed")