【Python库】02—ftplib

 ftplib是Python的内置库。该模块定义了class FTP。FTP类用于实现
文件传输协议(FTP)的客户端。

1.Telnet类

官方说明中,对Telnetlib库中Telnet类的介绍:

class ftplib.FTP(host=”, user=”, passwd=”, acct=”, timeout=None, source_address=None)
Return a new instance of the FTP class. When host is given, the method call connect(host) is made. When user is given, additionally the method call login(user, passwd, acct) is made (where passwd and acct default to the empty string when not given). The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if is not specified, the global default timeout setting will be used). source_address is a 2-tuple (host, port) for the socket to bind to as its source address before connecting.

2.FTP类中方法

 方法中,对应文件的处理主要有两种类型:
 Text files 和 Binary files,在指令用分别用lines和binary区分。

    Text files --> lines ;
    Binary files --> binary ;
  • ### 连接类

2.1 FTP.set_debuglevel(level)

Set the instance’s debugging level. This controls the amount of debugging output printed. The default, 0, produces no debugging output. A value of 1 produces a moderate amount of debugging output, generally a single line per request. A value of 2 or higher produces the maximum amount of debugging output, logging each line sent and received on the control connection.

 请求反馈的打印情况,可以试一试效果。默认值为0。(一般可以不使用,在调试时使用)

2.2 FTP.connect(host=”, port=0, timeout=None, source_address=None)

Connect to the given host and port. The default port number is 21, as specified by the FTP protocol specification. It is rarely needed to specify a different port number. This function should be called only once for each instance; it should not be called at all if a host was given when the instance was created. All other methods can only be used after a connection has been made. The optional timeout parameter specifies a timeout in seconds for the connection attempt. If no timeout is passed, the global default timeout setting will be used. source_address is a 2-tuple (host, port) for the socket to bind to as its source address before connecting.

 一般不用指定端口port,默认为21。对于timeout参数理解还不够。

2.3 FTP.getwelcome()

 返回连接成功信息。

2.4 FTP.login(user=’anonymous’, passwd=”, acct=”)

 passwd和acct<可选用>

Log in as the given user. The passwd and acct parameters are optional and default to the empty string. If no user is specified, it defaults to ‘anonymous’. If user is ‘anonymous’, the default passwd is ‘anonymous@’. This function should be called only once for each instance, after a connection has been established; it should not be called at all if a host and user were given when the instance was created. Most FTP commands are only allowed after the client has logged in. The acct parameter supplies “accounting information”; few systems implement this.

扫描二维码关注公众号,回复: 3496668 查看本文章

2.4 FTP.sendcmd(cmd)

Send a simple command string to the server and return the response string.

2.5 FTP.quit()

Send a QUIT command to the server and close the connection. This is the “polite” way to close a connection, but it may raise an exception if the server responds with an error to the QUIT command. This implies a call to the close() method which renders the FTP instance useless for subsequent calls (see below).

2.6 FTP.close()

Close the connection unilaterally. This should not be applied to an already closed connection such as after a successful call to quit(). After this call the FTP instance should not be used any more (after a call to close() or quit() you cannot reopen the connection by issuing another login() method).

2.5和2.6的区别:
- FTP.quit():发送QUIT命令给服务器,并关闭连接。这是一个比较“缓和”的关闭连接的方式。
- FTP.close():客户端单方面关闭连接。

  • ### 文件传输类

2.7 FTP.retrbinary(cmd, callback, blocksize=8192, rest=None)

Retrieve a file in binary transfer mode. cmd should be an appropriate RETR command: ‘RETR filename’. The callback function is called for each block of data received, with a single bytes argument giving the data block. The optional blocksize argument specifies the maximum chunk size to read on the low-level socket object created to do the actual transfer (which will also be the largest size of the data blocks passed to callback). A reasonable default is chosen. rest means the same thing as in the transfercmd() method.

 使用二进制传输方式,检索一个文件。
这一部分没有懂。

Demo1:

ftp.retrbinary('RETR README', open('README', 'wb').write)

2.8 FTP.retrlines(cmd, callback=None)

Retrieve a file or directory listing in ASCII transfer mode. cmd should be an appropriate RETR command (see retrbinary()) or a command such as LIST or NLST (usually just the string ‘LIST’). LIST retrieves a list of files and information about those files. NLST retrieves a list of file names. The callback function is called for each line with a string argument containing the line with the trailing CRLF stripped. The default callback prints the line to sys.stdout.

2.9 FTP.storbinary(cmd, fp, blocksize=8192, callback=None, rest=None)

Store a file in binary transfer mode. cmd should be an appropriate STOR command: “STOR filename”. fp is a file object (opened in binary mode) which is read until EOF using its read() method in blocks of size blocksize to provide the data to be stored. The blocksize argument defaults to 8192. callback is an optional single parameter callable that is called on each block of data after it is sent. rest means the same thing as in the transfercmd() method.

2.10 FTP.storlines(cmd, fp, callback=None)

Store a file in ASCII transfer mode. cmd should be an appropriate STOR command (see storbinary()). Lines are read until EOF from the file object fp (opened in binary mode) using its readline() method to provide the data to be stored. callback is an optional single parameter callable that is called on each line after it is sent.
- ### 文件修改类

这一部分做成表格

方法名称 作用
FTP.rename(oldname,newname) 文件重命名
FPT.delete(filename) 删除文件
FTP.cwd(filepath) 设置当前路径
FTP.mkd(filepath) 创建新路径
FTP.pwd 返回路径名称
FTP.rmd(dirname) 删除指定路径
FTP.size(filename)

2.11 FTP.rename(fromname, toname)

Rename file fromname on the server to toname.

2.12 FTP.delete(filename)

Remove the file named filename from the server. If successful, returns the text of the response, otherwise raises error_perm on permission errors or error_reply on other errors.

2.13 FTP.cwd(pathname)

Set the current directory on the server.

2.14 FTP.mkd(pathname)

Create a new directory on the server.

2.15 FTP.pwd()

Return the pathname of the current directory on the server.

2.16 FTP.rmd(dirname)

Remove the directory named dirname on the server.

2.17 FTP.size(filename)

Request the size of the file named filename on the server. On success, the size of the file is returned as an integer, otherwise None is returned. Note that the SIZE command is not standardized, but is supported by many common server implementations.

3. Demo

Demo1:连接服务器

ftp=FTP()                        #设置FTP
ftp.connect("IP_addr","port")    #连接FTP
ftp.login("user","password")     #登陆

Demo2:上传文件

fp=open('D:/test.txt','rb')      
cmd='STOR filepath/test.txt'
ftp.storbinary(cmd, fp)

说明:
- fp: 一个打开的文件对象,‘rb’以二进制形式打开文件
- storbinary是以二进制形式上传文件。
- STOR,是FTP的一个命令,后面需要加上保存文件的路径及文件名
Demo3:下载文件

ftp.nlst(path) #获取目录下的文件
file_handle=open(filename,"wb").write  #以写模式在本地打开文件
ftp.retrbinaly("RETR filename.txt",file_handle)   #接收服务器上文件并写入本地文件

说明:
- nlst: 一个打开的文件对象,‘rb’以二进制形式打开文件
- storbinary是以二进制形式上传文件。
- RETR,是FTP的一个命令,后面需要加上保存文件的路径及文件名

官网例子:

import getpass
import sys
import telnetlib

HOST = "localhost"
user = raw_input("Enter your remote account: ")
password = getpass.getpass()

tn = telnetlib.Telnet(HOST)

tn.read_until("login: ")
tn.write(user + "\n")
if password:
    tn.read_until("Password: ")
    tn.write(password + "\n")

tn.write("ls\n")
tn.write("exit\n")

print tn.read_all()

其他Demo1:

from ftplib import FTP      # 加载ftp模块
ftp = FTP()                 # 获取FTP对象
ftp.set_debuglevel(2)       # 打开调试级别2,显示详细信息
ftp.connect('IP', PORT)     # 连接ftp,server和端口
ftp.login('user', 'password')  # 登录用户
print(ftp.getwelcome())     # 打印欢迎信息
ftp.cmd('xxx/xxx')          # 进入远程目录
bufsize = 1024              # 设置缓存区大小
filename='filename.txt'     # 需要下载的文件
file_handle=open(filename, 'wb').write   # 以写的模式在本地打开文件
file.retrbinaly('RETR filename.txt', file_handle,bufsize)  # 接收服务器上文件并写入本地文件
ftp.set_debuglevel(0)       # 关闭调试模式
ftp.quit                    # 退出ftp

Demo2:

from ftplib import FTP
import time
import tarfile

from ftplib import FTP

def ftpconnect(host, username, password)
    ftp = FTP()
    ftp.connect(host, 21)
    ftp.login(username, password)
    return ftp

def downloadfile(ftp, remotepath, localpath):
    bufsize = 1024
    fp = open(localpath, 'wb')
    ftp.retrbinary('RETR'+remotepath, fp.write, bufsize)

    ftp.set_debuglevel(0)
    fp.close()

def uploadfile(ftp, remotepath, localpath):
    bufsize = 1024
    fp = open(localpath, 'rb')
    ftp.storbinary('STOR'+remotepath, fp, bufsize)
    ftp.set_debuglevel(0)
    fp.close()

if __name__ == '__main__':
    ftp = ftpconnect("******", "***", "***")
    downloadfile(ftp, "***", "***")
    uploadfile(ftp, "***", "***")

    ftp.quit()

Reference:
1.Python官网介绍:20.14. filelib — FTP protocol client
https://docs.python.org/3/library/ftplib.html
2.FTP操作
https://www.testwo.com/blog/7270
https://blog.csdn.net/alizej/article/details/78658372
3.扩展:pyftplib
https://www.cnblogs.com/stacklike/p/8119879.html

猜你喜欢

转载自blog.csdn.net/Neocst/article/details/79875015