Python ftplib - specify port
Asked Answered
D

4

31

I would like to specify the port with Python's ftplib client (instead of default port 21).

Here is the code:

from ftplib import FTP
ftp = FTP('localhost') # connect to host, default port

Is there an easy way to specify an alternative port?

Dioptrics answered 20/6, 2013 at 2:15 Comment(0)
F
26
>>> from ftplib import FTP
>>> HOST = "localhost"
>>> PORT = 12345 # Set your desired port number
>>> ftp = FTP()
>>> ftp.connect(HOST, PORT)
Felicitasfelicitate answered 20/6, 2013 at 2:19 Comment(0)
C
14

After searching numerous solutions, a combination of the docs.python.org and the connect command solved my issue.

from ftplib import FTP_TLS

host = 'host'
port = 12345
usr = 'user'
pwd = 'password'
ftps = FTP_TLS()
ftps.connect(host, port)
# Output: '220 Server ready for new user.'
ftps.login(usr, pwd)
# Output: '230 User usr logged in.'
ftps.prot_p()
# Output: '200 PROT command successful.'
ftp.nlst()
# Output: ['mysubdirectory', 'mydoc']

If you're using plain FTP instead of FTPS, just use ftplib.FTP instead.

Cammiecammy answered 15/9, 2017 at 18:6 Comment(0)
A
8

Yes you can use connect

from ftplib import FTP

my_ftp = FTP()
my_ftp.connect('localhost', 80) # 80 is the port for example
Apriorism answered 20/6, 2013 at 2:19 Comment(0)
D
6

Found the answer. Instantiate the FTP object and then run connect on it like so:

from ftplib import FTP
ftp = FTP()
ftp.connect('localhost', 2121)
Dioptrics answered 20/6, 2013 at 2:19 Comment(1)
8 years later and Doco still not reflecting this usage.Wester

© 2022 - 2024 — McMap. All rights reserved.