#!/usr/bin/evn python
from ftplib import FTP_TLS, FTP
import socket
import ssl
import os
import sys
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)
#建立服务器的FTPS连接
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:
#创建socket
self.sock = socket.create_connection((self.host, self.port), self.timeout)
self.af = self.sock.family
#wrap_socket接收一个socket实例,返回SSLSocket实例,可以理解在普通socket上封装了一层ssl
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 get_ftp_ver(version):
#如果没有这个目录就新建
if not os.path.isdir(version):
os.makedirs(version)
ftps = IMPLICIT_FTP_TLS()
ftps.connect(host='10.0.0.8', port=666)
ftps.login(user="ftp_user", passwd="ftp_password")
#建立安全的数据连接,之后才能返回数据。
ftps.prot_p()
ftps.cwd(version)
files = ftps.nlst()
#进入本地目录
os.chdir(version)
#循环下载每个文件
for file in files:
fp = open(file, 'wb')
ftps.retrbinary('RETR %s' % file, fp.write)
ftps.close()
if __name__ == '__main__':
get_ftp_ver(sys.argv[1])