如何在 Python 中连接到 FTP 服务器?

问题描述

当我尝试连接到 ftp 服务器时遇到问题,我使用的是带有 BigSur 和 python3 的 Mac。

这是我的代码

import ftplib

FTP_HOST = "ftp://myserver"
FTP_USER = "user"
FTP_PASS = "pass"

# connect to the FTP server
ftp = ftplib.FTP(FTP_HOST,FTP_USER,FTP_PASS)

这里返回的是:


Traceback (most recent call last):
  File "/Users/adrianrodriguezgalisteo/jonsuGo/test_upload.py",line 8,in <module>
    ftp = ftplib.FTP(FTP_HOST,FTP_PASS)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/ftplib.py",line 119,in __init__
    self.connect(host)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/ftplib.py",line 156,in connect
    self.sock = socket.create_connection((self.host,self.port),self.timeout,File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socket.py",line 822,in create_connection
    for res in getaddrinfo(host,port,SOCK_STREAM):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socket.py",line 953,in getaddrinfo
    for res in _socket.getaddrinfo(host,family,type,proto,flags):
socket.gaierror: [Errno 8] nodename nor servname provided,or not kNown

我只想连接到服务器并上传文件

谢谢。

解决方法

https://docs.python.org/3/library/ftplib.html 主机应该只是 myserver

FTP_HOST = "myserver"

您可能需要服务器名称的 FQDN