Search code examples
pythondownloadftpftplib

Python FTP download fails with "421 Timeout - try typing a little faster next time"


I have my domain on a server and the server runs a script each night to perform a backup. The backup is saved on the server in a specific location with the date appended to the end of the filename and in a .tgz format.

My goal is to log into the server via FTP and download the backup file and sane it locally. My script so far:

from ftplib import FTP
import fnmatch

ftp = FTP('ftp.mydomain.com')

ftp.login('[email protected]', 'mypassword')

files = ftp.nlst()

for file in files:
    if fnmatch.fnmatch(file, '*tgz'):
        print("Downloading..." + file)
        
        try:
            ftp.retrbinary("RETR" + file, open("/home/PiEight/" + file, 'wb').write)
            
        except EOFError:
            pass
ftp.close()

When I run the script, I get :

Downloading...mysite_backup_01-Mar-2023.tgz

Then, after several minutes, I get:

ftplib.error_temp: 421 Timeout - try typing a little faster next time

The script is finding the correct file and beginning the download but that's it. The file is created locally but it is always 0 bytes. Can someone please give me some insight as to the problem and suggestions?


Solution

  • You are missing a space between the RETR and the file. Moreover you fail to close the local file. The correct code should be:

    with open("/home/PiEight/" + file, 'wb') as f:
        ftp.retrbinary("RETR " + file, f.write)
    

    See How to download a file via FTP with Python ftplib