wawawa
wawawa

Reputation: 3345

Exception handling using ftplib package in Python

I'm new to ftplib and FTP in Python, I'm testing a simple script provided by the documentation: https://docs.python.org/3/library/ftplib.html#ftplib.error_reply

try:
    ftp = ftplib.FTP('ftp.us.debian.org')
    ftp.login('111', '111')
except ftplib.all_errors as err:
    print(f'Error: ' + str(err))

This returns Error: 503 Login with USER first., if I add ftp.set_debuglevel(2) this will tell me more detailed info:

*cmd* 'USER 111'
*put* 'USER 111\r\n'
*get* '331 This FTP server is anonymous only.\n'
*resp* '331 This FTP server is anonymous only.'
*cmd* 'PASS ***'
*put* 'PASS ***\r\n'
*get* '503 Login with USER first.\n'
*resp* '503 Login with USER first.'
Error: 503 Login with USER first.

It tells me additional info like This FTP server is anonymous only.

So I also tried:

try:
    ftp = ftplib.FTP('ftp.us.debian.org')
except ftplib.all_errors as err:
    print(f'Error: ' + str(err))
try:
    #ftp.set_debuglevel(2)
    ftp.login('111', '111')
except ftplib.all_errors as err:
    print(f'Error: ' + str(err))

This still won't tell me This FTP server is anonymous only I wonder if I'm missing something, and can someone tell me what's the best practice to do exception handeling for FTP? Any examples? Many thanks.

Upvotes: 0

Views: 666

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 148890

The error is not really related to ftplib but to the so called ftp anonymous mode.

FTP is a rather old protocol, and it requires the client to present credentials to the server. It was not suited for public servers, so the special ftp or anonymous(*) user was used for anonymous logging (this is optional for most FTP servers). Usage was to pass either ftp as the password, or the user mail address to let the server admin know who used their service.

So here you should use:

try:
    ftp = ftplib.FTP('ftp.us.debian.org')
    ftp.login('ftp', 'ftp')     # or ftp.login('anonymous', 'guest')
except ftplib.all_errors as err:
    print(f'Error: ' + str(err))

RFC 1635 only defines the user anonymous and recommend guest password, but most of the servers I have used also accepted ftp

Upvotes: 2

Related Questions