FTP(File Transfer Protocol)文件传输协议是最常用的Internet协议之一,它定义了基于通过套接字交换命令字符串和文件内容的高级对话模型。
FTP运行在两个套接字的上层:一个套接字用于在客户端和服务器之间传输控制命令,另一个套接字用于传输字节。通过使用两个套接字模型,FTP避免了发生死锁的可能。
ftplib模块简单说明
使用fitlib连接FTP服务器
简便写法(默认端口)
import ftplib,socket
# FTP服务器域名或者IP地址
default_host = '127.0.0.1'
default_user = 'Test'
default_pswd = '123456'
print('Connecting %s ...'%default_host)
try:
ftp_connection = ftplib.FTP(default_host ,default_user ,default_pswd ,10)
# 使用GBK防止乱码
# ftp_connection.encoding = 'utf-8' #UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbb in position 4: invalid start byte
ftp_connection.encoding = 'gbk'
except (socket.error, socket.gaierror):
print('Error: can not connect %s %d' % (default_host , default_port))
except (ftplib.error_perm):
print('Error: user Authentication failed')
else:
print(ftp_connection.getwelcome())
另一种写法
import ftplib,socket
# FTP服务器域名或者IP地址
default_host = '127.0.0.1'
# FTP服务端口号
default_port = 2111
default_user = 'Test'
default_pswd = '123456'
print('Connecting %s ...'%default_host)
ftp_connection = ftplib.FTP()
# 使用GBK防止乱码
# ftp_connection.encoding = 'utf-8' #UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbb in position 4: invalid start byte
ftp_connection.encoding = 'gbk'
try:
ftp_connection.connect(default_host ,default_port )
ftp_connection.login(default_user ,default_pswd )
except (socket.error, socket.gaierror):
print('Error: can not connect %s %d' % (default_host , default_port))
except (ftplib.error_perm):
print('Error: user Authentication failed')
else:
print(ftp_connection.getwelcome())
查看FTP服务器列表并下载文件
import getpass,ftplib,getpass
#是否强制服务器进入主动FTP模式,默认False
non_passive = False
# FTP服务器域名或者IP地址
default_Host = '127.0.0.1'
# FTP服务端口号
default_Port = 2111
default_User = 'Test'
default_Pswd = '123456'
dir_Name = '.'
file_Name = 'test.TXT'
def getConnect(host=default_Host,port=default_Port,user=default_User,pswd=default_Pswd):
user_name = input('Username?') if not user else user
user_pswd = input('Password?') if not pswd else pswd
#使用getpass模块获取输入,功能类似input
#user_pswd = getpass.getpass('Password?')
print('Connecting %s ...'%host)
ftp_connection = ftplib.FTP()
ftp_connection.encoding = 'gbk'
try:
ftp_connection.connect(host,port)
ftp_connection.login(user_name,user_pswd)
except (socket.error, socket.gaierror):
print('Error: can not connect %s %d' % (user_name, user_pswd))
return None
except ftplib.error_perm:
print('Error: user Authentication failed')
return None
else:
print(ftp_connection.getwelcome())
return ftp_connection
ftp = getConnect()
ftp.cwd(dir_Name)
if ftp:
if non_passive:
ftp.set_pasv(False)
ftp_connection.cwd(dir_Name)
ftp_connection.retrlines('LIST')
print('Downloading ...')
local_file = open(file_Name,'wb')
ftp_connection.retrbinary('RETR '+file_Name,local_file.write,1024)
ftp_connection.quit()
local_file.close()