Bootstrap FreeKB - Python (Scripting) - Connect to an FTP Server
Python (Scripting) - Connect to an FTP Server

Updated:   |  Python (Scripting) articles

The ftp module can be used to connect to an FTP server. Here is the minimal boilterplate code without error handling.

#!/usr/bin/python3
from ftplib import FTP

global ftp
hostname = "ftp server hostname"
username = "username to connect to the ftp server"
password = "password to connect to the ftp server"

ftp = FTP(hostname, user=username, passwd=password)
print(ftp)

 

Here is a more practical example, with try/except/else error handling

#!/usr/bin/python3
from ftplib import FTP

global ftp
hostname = "ftp server hostname"
username = "username to connect to the ftp server"
password = "password to connect to the ftp server"

try:
  ftp = FTP(hostname, user=username, passwd=password)
except Exception as exception:
  print(exception)
else:
  print(ftp)

 

If the connection fails, something like this should be returned.

Traceback (most recent call last):
  File "test.py", line 6, in <module>
    ftp = FTP(hostname, user=username, passwd='bogus')
  File "/usr/lib64/python2.7/ftplib.py", line 122, in __init__
    self.login(user, passwd, acct)
  File "/usr/lib64/python2.7/ftplib.py", line 393, in login
    if resp[0] == '3': resp = self.sendcmd('PASS ' + passwd)
  File "/usr/lib64/python2.7/ftplib.py", line 249, in sendcmd
    return self.getresp()
  File "/usr/lib64/python2.7/ftplib.py", line 224, in getresp
    raise error_perm, resp
ftplib.error_perm: 530 Login authentication failed

 

On the other hand, if the connection is successful, something like this should be returned.

<ftplib.FTP instance at 0x7f1608ef9d40>

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter fae02e in the box below so that we can be sure you are a human.