Search code examples
pythonproxyftplib

Python ftplib - connecting through a proxy with custom port


My question then, is how do I modify the connection string to cater for the particulars that my firewall is expecting?

This one is a little bit of a compound issue.

  1. I am connecting from behind an enterprise proxy. I can successfully connect using Filezilla. More info below.
  2. The proxy has a custom port through which I need to connect: 8021.

I'm no ftplib guru, but this is what I have worked out so far:


    import ftplib
    from dateutil import parser
    
    host_proxy = 'our.proxy.internal'
    host_port = 8021
    
    ftp_user = 'username'
    ftp_pass = 'password'
    ftp_host = 'ftp.thesite.com'
    
    u = "user %s@%s" % (ftp_user, ftp_host)
    p = "pass %s" % (ftp_pass)
    
    print(u)
    print(p)
    
    ftp = ftplib.FTP(host_proxy, host_port, u, p)

This setup fails with an error: ConnectionRefusedError No connection could be made because the target machine actively refused it.

This is progress!

The Filezilla custom FTP proxy setup is as follows:


    user %u@%h 
    pass %p

Where:

%u = ftp_user   
%h = ftp_host   
%p = ftp_pass   
Proxy Host = our.proxy.internal

The split across 2 lines is important, apparently.


Solution

  • This works, for the scenario posted:

    import ftplib
    from dateutil import parser
    
    #proxy details
    host_proxy = 'organisation.silly.proxy'
    host_port = 8021
    
    #ftp details
    ftp_user = 'ftpusername'
    ftp_pass = 'ftppassword'
    ftp_host = 'ftp.thesite.com'
    
    ftp_loginstring = ftp_user + "@" + ftp_host 
    
    ftp = FTP()
    ftp.set_debuglevel(1)
    ftp.connect(host_proxy, host_port)
    ftp.login(user=ftp_loginstring, passwd=ftp_pass)
    
    
    print("Logged in ok")