我有一个需要连接到我能够成功连接使用的lftp FTPS服务器。 然而,当我尝试使用Python ftplib.FTP_TLS,超时,堆栈跟踪表明,它正在等待服务器发送欢迎信息或喜欢。 有谁知道什么问题,以及如何克服? 我不知道是否有需要在服务器端做了什么,而是怎么来lftp的客户端工作正常。 任何帮助是极大的赞赏。
这里是堆栈跟踪:
ftp = ftplib.FTP_TLS()
ftp.connect(cfg.HOST, cfg.PORT, timeout=60)
File "C:\Users\username\Softwares\Python27\lib\ftplib.py", line 135, in connect
self.welcome = self.getresp()
File "C:\Users\username\Softwares\Python27\lib\ftplib.py", line 210, in getresp
resp = self.getmultiline()
File "C:\Users\username\Softwares\Python27\lib\ftplib.py", line 196, in getmultiline
line = self.getline()
File "C:\Users\username\Softwares\Python27\lib\ftplib.py", line 183, in getline
line = self.file.readline()
File "C:\Users\username\Softwares\Python27\lib\socket.py", line 447, in readline
data = self._sock.recv(self._rbufsize)
socket.timeout: timed out
使用lftp的相同的FTPS服务器成功登录:
$ lftp
lftp :~> open ftps://ip_address:990
lftp ip_address:~> set ftps:initial-prot P
lftp ip_address:~> login ftps_user_id ftps_user_passwd
lftp sftp_user_id@ip_address:~> ls
ls: Fatal error: SSL_connect: self signed certificate
lftp ftps_user_id@ip_address:~> set ssl:verif-certificate off
lftp ftps_user_id@ip_address:~> ls
lftp ftps_user_id@ip_address:/>
顺便说一句,我使用Python 2.7.3。 我做了不少使用谷歌搜索,但没有发现任何有用的。
我仍然有这个问题,感激,如果有人可以提供帮助。 从服务器密切关注的FTP.connect()到服务器的连接是没有问题的,但得到确认(或欢迎信息)是一个问题。 lftp的没有这个问题,FileZilla中没有任何问题,无论是作为这里的日志 -
Status: Connecting to xx.xx.xx.xxx:990...
Status: Connection established, initializing TLS...
Status: Verifying certificate...
Status: TLS/SSL connection established, waiting for welcome message...
Response: 220- Vous allez vous connecter sur un serveur prive
Response: 220- Seules les personnes habilitees y sont autorisees
Response: 220 Les contrevenants s'exposent aux poursuites prevues par la loi.
Command: USER xxxxxxxxxxxxx
Response: 331 Password required for xxxxxxxxxxxxx.
Command: PASS **********
Response: 230 Login OK. Proceed.
Command: PBSZ 0
Response: 200 PBSZ Command OK. Protection buffer size set to 0.
Command: PROT P
Response: 200 PROT Command OK. Using Private data connection
Status: Connected
Status: Retrieving directory listing...
Command: PWD
Response: 257 "/" is current folder.
Command: TYPE I
Response: 200 Type set to I.
Command: PASV
Response: 227 Entering Passive Mode (81,93,20,199,4,206).
Command: MLSD
Response: 150 Opening BINARY mode data connection for MLSD /.
Response: 226 Transfer complete. 0 bytes transferred. 0 bps.
Status: Directory listing successful
Answer 1:
我同样的问题工作了半天,终于想通了。
对于隐含的FTP TLS / SSL(defualt端口990),我们的客户端程序必须建立在创建套接字之后,权TLS / SSL连接。 但是Python的类FTP_TLS
不重新从类FTP的连接功能。 我们需要修理它:
class tyFTP(ftplib.FTP_TLS):
def __init__(self,
host='',
user='',
passwd='',
acct='',
keyfile=None,
certfile=None,
timeout=60):
ftplib.FTP_TLS.__init__(self,
host=host,
user=user,
passwd=passwd,
acct=acct,
keyfile=keyfile,
certfile=certfile,
timeout=timeout)
def connect(self, host='', port=0, timeout=-999):
"""Connect to host. Arguments are:
- host: hostname to connect to (string, default previous host)
- port: port to connect to (integer, default previous port)
"""
if host != '':
self.host = host
if port > 0:
self.port = port
if timeout != -999:
self.timeout = timeout
try:
self.sock = socket.create_connection((self.host, self.port), self.timeout)
self.af = self.sock.family
# add this line!!!
self.sock = ssl.wrap_socket(self.sock,
self.keyfile,
self.certfile,
ssl_version=ssl.PROTOCOL_TLSv1)
# add end
self.file = self.sock.makefile('rb')
self.welcome = self.getresp()
except Exception as e:
print(e)
return self.welcome
这个派生类的重载连接功能,并建立套接字TLS周围的包装。 在成功连接并登录到FTP服务器,你需要调用: FTP_TLS.prot_p()
执行任何FTP命令之前!
希望这将帮助^ _ ^
Answer 2:
扩展已迄今提出的解决方案,这个问题是隐性FTPS连接需要的插座自动SSL包裹,我们得到一个机会来调用login()前。 很多人都建议在连接方法的情况下做到这一点的子类,我们可以更一般通过用财产上设定的自动换行修改了get / set self.sock的管理这样的:
import ftplib
import ssl
class ImplicitFTP_TLS(ftplib.FTP_TLS):
"""FTP_TLS subclass that automatically wraps sockets in SSL to support implicit FTPS."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._sock = None
@property
def sock(self):
"""Return the socket."""
return self._sock
@sock.setter
def sock(self, value):
"""When modifying the socket, ensure that it is ssl wrapped."""
if value is not None and not isinstance(value, ssl.SSLSocket):
value = self.context.wrap_socket(value)
self._sock = value
用法基本相同,与标准FTP_TLS类:
ftp_client = ImplicitFTP_TLS()
ftp_client.connect(host='ftp.example.com', port=990)
ftp_client.login(user='USERNAME', passwd='PASSWORD')
ftp_client.prot_p()
Answer 3:
在NERV的响应扩展 - 这让我无比,这里是我如何能够解决我的问题在端口990需要身份验证的隐式TLS连接。
文件名:ImplicitTLS.py
from ftplib import FTP_TLS
import socket
import ssl
class tyFTP(FTP_TLS):
def __init__(self, host='', user='', passwd='', acct='', keyfile=None, certfile=None, timeout=60):
FTP_TLS.__init__(self, host, user, passwd, acct, keyfile, certfile, timeout)
def connect(self, host='', port=0, timeout=-999):
if host != '':
self.host = host
if port > 0:
self.port = port
if timeout != -999:
self.timeout = timeout
try:
self.sock = socket.create_connection((self.host, self.port), self.timeout)
self.af = self.sock.family
self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile, ssl_version=ssl.PROTOCOL_TLSv1)
self.file = self.sock.makefile('rb')
self.welcome = self.getresp()
except Exception as e:
print e
return self.welcome
然后从我的主要应用程序,我这样做:
from ImplicityTLS import tyFTP
server = tyFTP()
server.connect(host="xxxxx", port=990)
server.login(user="yyyy", passwd="fffff")
server.prot_p()
而就是这样,我能下载文件等道具去NERV为原来的答案。
Answer 4:
通过NERV答案和布拉德·德克尔样品是真的很有帮助。 荣誉给他们。 他们救了我小时。
Unfortunetely,最初它并没有为我工作。
就我而言,只是工作一旦连接我删除了ssl_version
从参数ssl.wrap_socket
方法。 此外,为了将任何命令发送到服务器,我不得不覆盖ntransfercmd
从方法FTP_TLS
类和删除ssl_version
太参数存在。
这是为我工作的代码:
from ftplib import FTP_TLS, FTP
import socket
import ssl
class IMPLICIT_FTP_TLS(FTP_TLS):
def __init__(self, host='', user='', passwd='', acct='', keyfile=None,
certfile=None, timeout=60):
FTP_TLS.__init__(self, host, user, passwd, acct, keyfile, certfile, timeout)
def connect(self, host='', port=0, timeout=-999):
'''Connect to host. Arguments are:
- host: hostname to connect to (string, default previous host)
- port: port to connect to (integer, default previous port)
'''
if host != '':
self.host = host
if port > 0:
self.port = port
if timeout != -999:
self.timeout = timeout
try:
self.sock = socket.create_connection((self.host, self.port), self.timeout)
self.af = self.sock.family
self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
self.file = self.sock.makefile('rb')
self.welcome = self.getresp()
except Exception as e:
print (e)
return self.welcome
def ntransfercmd(self, cmd, rest=None):
conn, size = FTP.ntransfercmd(self, cmd, rest)
if self._prot_p:
conn = ssl.wrap_socket(conn, self.keyfile, self.certfile)
return conn, size
而强制性的示例:
>>> ftps = IMPLICIT_FTP_TLS()
>>> ftps.connect(host='your.ftp.host', port=990)
>>> ftps.login(user="your_user", passwd="your_passwd")
>>> ftps.prot_p()
>>> ftps.retrlines('LIST')
Answer 5:
隐FTP通过TLS使用被动传输模式
下面是一个实现多一点点“工业”。
我们注意到,在前面的例子名为“语境”的属性在init失踪。
该代码波纹管工作完全都与Python 2.7和Python 3
代码
import ftplib, socket, ssl
FTPTLS_OBJ = ftplib.FTP_TLS
# Class to manage implicit FTP over TLS connections, with passive transfer mode
# - Important note:
# If you connect to a VSFTPD server, check that the vsftpd.conf file contains
# the property require_ssl_reuse=NO
class FTPTLS(FTPTLS_OBJ):
host = "127.0.0.1"
port = 990
user = "anonymous"
timeout = 60
logLevel = 0
# Init both this and super
def __init__(self, host=None, user=None, passwd=None, acct=None, keyfile=None, certfile=None, context=None, timeout=60):
FTPTLS_OBJ.__init__(self, host, user, passwd, acct, keyfile, certfile, context, timeout)
# Custom function: Open a new FTPS session (both connection & login)
def openSession(self, host="127.0.0.1", port=990, user="anonymous", password=None, timeout=60):
self.user = user
# connect()
ret = self.connect(host, port, timeout)
# prot_p(): Set up secure data connection.
try:
ret = self.prot_p()
if (self.logLevel > 1): self._log("INFO - FTPS prot_p() done: " + ret)
except Exception as e:
if (self.logLevel > 0): self._log("ERROR - FTPS prot_p() failed - " + str(e))
raise e
# login()
try:
ret = self.login(user=user, passwd=password)
if (self.logLevel > 1): self._log("INFO - FTPS login() done: " + ret)
except Exception as e:
if (self.logLevel > 0): self._log("ERROR - FTPS login() failed - " + str(e))
raise e
if (self.logLevel > 1): self._log("INFO - FTPS session successfully opened")
# Override function
def connect(self, host="127.0.0.1", port=990, timeout=60):
self.host = host
self.port = port
self.timeout = timeout
try:
self.sock = socket.create_connection((self.host, self.port), self.timeout)
self.af = self.sock.family
self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
self.file = self.sock.makefile('r')
self.welcome = self.getresp()
if (self.logLevel > 1): self._log("INFO - FTPS connect() done: " + self.welcome)
except Exception as e:
if (self.logLevel > 0): self._log("ERROR - FTPS connect() failed - " + str(e))
raise e
return self.welcome
# Override function
def makepasv(self):
host, port = FTPTLS_OBJ.makepasv(self)
# Change the host back to the original IP that was used for the connection
host = socket.gethostbyname(self.host)
return host, port
# Custom function: Close the session
def closeSession(self):
try:
self.close()
if (self.logLevel > 1): self._log("INFO - FTPS close() done")
except Exception as e:
if (self.logLevel > 0): self._log("ERROR - FTPS close() failed - " + str(e))
raise e
if (self.logLevel > 1): self._log("INFO - FTPS session successfully closed")
# Private method for logs
def _log(self, msg):
# Be free here on how to implement your own way to redirect logs (e.g: to a console, to a file, etc.)
print(msg)
用法示例
host = "www.myserver.com"
port = 990
user = "myUserId"
password = "myPassword"
myFtps = FTPTLS()
myFtps.logLevel = 2
myFtps.openSession(host, port, user, password)
print(myFtps.retrlines("LIST"))
myFtps.closeSession()
输出示例
INFO - FTPS connect() done: 220 (vsFTPd 3.0.2)
INFO - FTPS prot_p() done: 200 PROT now Private.
INFO - FTPS login() done: 230 Login successful.
INFO - FTPS session successfully opened
-rw------- 1 ftp ftp 86735 Mar 22 16:55 MyModel.yaml
-rw------- 1 ftp ftp 9298 Mar 22 16:55 MyData.csv
226 Directory send OK.
INFO - FTPS close() done
INFO - FTPS session successfully closed
Answer 6:
我知道这个线程是很老和ftp是不是受欢迎,因为它曾经是,但不管怎么说,如果它可以帮助任何人,我想作出额外的贡献。 我遇到了类似的情况试图连接到使用隐式(端口990)在被动模式下FTPS FTP服务器。 在这种情况下,服务器的初始连接进行协商之后,通常会提供一个新的主机的IP地址和端口,从用于进行初始连接时,通过其实际数据传输都应该发生的那些可能不同。 没什么大不了的,FTPS客户,包括Python,可以解决这个问题,只有这个特定的服务器提供了一个不可路由的(可能是内部的防火墙)的IP地址。 我注意到的FileZilla连接没有问题,但蟒蛇FTPLIB不能。 然后,我就遇到了这个主题:
如何更换与FTPLIB服务器地址的非路由的IP地址
该避让我,利用格热戈日Wierzowiecki方法我扩展方法暗示在该线程,并用此来了,这解决了我的问题。
import ftplib, os, sys
import socket
import ssl
FTPS_OBJ = ftplib.FTP_TLS
def conn_i_ftps(FTP_Site, Login_Name, Login_Password):
print "Starting IMPLICIT ftp_tls..."
ftps = tyFTP()
print ftps.connect(host=FTP_Site, port=990, timeout=120)
ftps.prot_p()
ftps.login(user=Login_Name, passwd=Login_Password)
print "Logged In"
ftps.retrlines('LIST')
# return ftps
class tyFTP(FTPS_OBJ):
def __init__(self, host='', user='', passwd='', acct='', keyfile=None, certfile=None, timeout=60):
FTPS_OBJ.__init__(self, host, user, passwd, acct, keyfile, certfile, timeout)
def connect(self, host='', port=0, timeout=-999):
if host != '':
self.host = host
if port > 0:
self.port = port
if timeout != -999:
self.timeout = timeout
try:
self.sock = socket.create_connection((self.host, self.port), self.timeout)
self.af = self.sock.family
self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
self.file = self.sock.makefile('rb')
self.welcome = self.getresp()
except Exception as e:
print e
return self.welcome
def makepasv(self):
print port #<---Show passively assigned port
print host #<---Show the non-routable, passively assigned IP
host, port = FTPS_OBJ.makepasv(self)
host = socket.gethostbyname(self.host) #<---- This changes the host back to the original IP that was used for the connection
print 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
print host #<----Showing the original IP
return host, port
然后代码被调用像这样
FTP_Site = "ftp.someserver.com"
Login_Name = "some_name"
Login_Password = "some_passwd"
conn_i_ftps(FTP_Site, Login_Name, Login_Password)
我想,一个可以换,其中主机被使用IF语句识别不可路由的地址,有点像这种变回线路:
if host.split(".")[0] in (10, 192, 172):
host = socket.gethostbyname(self.host)
.
.
.
文章来源: Python FTP implicit TLS connection issue