Skip to content
Advertisement

Controlling port numbers in use when connecting to FTP via Python’s ftplib behind a firewall

I’m trying to connect to a FTP server from behind a firewall that accepts outputs from the port range 6100–6200 only. I’m (rather naively, but based on a read of the documentation) trying:

JavaScript

But this gives the error:

JavaScript

From the same machine, I can successfully list the files using curl:

JavaScript

How can I connect to a regular (i.e. port 21) FTP server with ftplib circumventing my local firewall?

Advertisement

Answer

The curl --ftp-port switch enables the use of the active mode and sets the local listening ports to be used for incoming data connections.

That’s not what your code does. Your code uses the passive mode and sets source ports of outgoing control connection.


First, if you need to use the active mode, that generally means that your FTP server or your firewall is misconfigured. The active mode actually requires more firewall configuration than the passive mode. You should use the passive mode. That’s a way less work and more robust solution.

Note that in the passive mode, you cannot control the ports used, as that’s server’s decision, not client’s. You have to configure your local firewall (if any) to allow the data connection ports that the server is using.


If you really really need to use the active mode, use FTP.set_pasv.

JavaScript

The ftplib does not allow you to control the ports for the active mode. You would have to either edit the makeport method in the ftplib FTP class or override it in your code. Make it listen on a specific port in sock.bind:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement