Python ftplib - 指定端口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17204276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:45:43  来源:igfitidea点击:

Python ftplib - specify port

pythonftpftplib

提问by

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

我想用 Python 的 ftplib 客户端指定端口(而不是默认端口 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?

有没有一种简单的方法来指定替代端口?

回答by Gizmo

>>> from ftplib import FTP
>>> HOST = "localhost"
>>> PORT = 12345 # Set your desired port number
>>> ftp = FTP()
>>> ftp.connect(HOST, PORT)

回答by Gizmo

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

找到了答案。实例化 FTP 对象,然后像这样在其上运行连接:

from ftplib import FTP
ftp = FTP()
ftp.connect('localhost', 2121)

回答by Victor Castillo Torres

Yes you can use connect

是的,您可以使用连接

from ftplib import FTP

my_ftp = FTP()
my_ftp.connect('localhost', 80) # 80 is the port for example

回答by datalifenyc

After searching numerous solutions, a combination of the docs.python.organd the connectcommand solved my issue.

在搜索了许多解决方案后,docs.python.orgconnect命令的组合解决了我的问题。

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.FTPinstead.

如果您使用的是普通 FTP 而不是 FTPS,请ftplib.FTP改用。