脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|shell|

服务器之家 - 脚本之家 - Python - Python网络编程之ftplib模块

Python网络编程之ftplib模块

2023-02-22 12:13springsnow Python

这篇文章介绍了Python网络编程之ftplib模块,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

Python中默认安装的ftplib模块定义了FTP类,可用来实现简单的ftp客户端,用于上传或下载文件。

ftp登陆连接

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from ftplib import FTP  # 加载ftp模块
 
ftp = FTP()  # 设置变量
ftp.set_debuglevel(2# 打开调试级别2,显示详细信息
ftp.connect("10.126.64.14", 21# 连接的ftp sever和端口
ftp.login("usr_esop", "PWD4ftp@201903#")  # 连接的用户名,密码
print(ftp.getwelcome())  # 打印出欢迎信息
 
ftp.cwd("/ZS_ESOP/55-548410/-/zh/Split"# 更改远程目录
bufsize = 1024  # 设置的缓冲区大小
filename = "tslint.json"  # 需要下载的文件
file_handle = open(filename, "wb").write  # 以写模式在本地打开文件
ftp.retrbinary("RETR tslint.json", file_handle, bufsize)  # 接收服务器上文件并写入本地文件
ftp.set_debuglevel(0# 关闭调试模式
ftp.quit  # 退出ftp

ftp相关命令操作

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
ftp.cwd(pathname) #设置FTP当前操作的路径,cwd可以使用“..”,但不使用"./path"以及"../path"这样的相对路径
ftp.dir() #显示目录下文件信息
ftp.nlst() #获取目录下的文件
ftp.mkd(pathname) #新建远程目录
ftp.pwd() #返回当前所在位置
ftp.rmd(dirname) #删除远程目录
ftp.delete(filename) #删除远程文件
ftp.rename(fromname, toname)#将fromname修改名称为toname。可以带路径,起到移动文件的作用
ftp.storbinaly("STOR filename.txt",file_handel,bufsize) #以
BINARY
模式上传目标文件
ftp.storlines("STOR filename.txt",file_handel) #以ASCII模式存储文件
ftp.retrbinary("RETR filename.txt",file_handel,bufsize)#以
BINARY模式
下载FTP文件
FTP.retrlines("RETR filename.txt",file_handel) #以ASCII模式获取文件或者文件夹列表

FTP.quit()与FTP.close()的区别

  • FTP.quit():发送QUIT命令给服务器并关闭掉连接。这是一个比较“缓和”的关闭连接方式,但是如果服务器对QUIT命令返回错误时,会抛出异常。
  • FTP.close():单方面的关闭掉连接,不应该用在已经关闭的连接之后,例如不应用在FTP.quit()之后。

下载、上传文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from ftplib import FTP
 
 
def ftpconnect(host, username, password):
    ftp = FTP()
    # ftp.set_debuglevel(2)         #打开调试级别2,显示详细信息
    ftp.encoding = 'GB2312'  # 解决中文编码问题,默认是latin-1,如果将 encoding='utf-8'报错,可以 改为GB2312、gbk、ISO-8859-1
    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()

上传、下载文件/目录

:目录内为文件,若为目录则无法传输

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import os
import ftplib
 
 
class myFtp:
    ftp = ftplib.FTP()
    bIsDir = False
    path = ""
 
    def __init__(self, host, port='21'):
        # self.ftp.set_debuglevel(2) #打开调试级别2,显示详细信息
        # self.ftp.set_pasv(0)      #0主动模式 1 #被动模式
        self.ftp.encoding = 'GB2312'  # 解决中文编码问题,默认是latin-1,如果将 encoding='utf-8'报错,可以 改为GB2312、gbk、ISO-8859-1
        self.ftp.connect(host, port)
 
    def login(self, user, passwd):
        self.ftp.login(user, passwd)
        print(self.ftp.welcome)
 
    def down_load_file(self, local_file, remote_file):
        file_handler = open(local_file, 'wb')
        self.ftp.retrbinary("RETR %s" % remote_file, file_handler.write)
        file_handler.close()
        return True
 
    def up_load_file(self, local_file, remote_file):
        if not os.path.isfile(local_file):
            return False
        file_handler = open(local_file, "rb")
        self.ftp.storbinary('STOR %s' % remote_file, file_handler, 4096)
        file_handler.close()
        return True
 
    def up_load_file_tree(self, local_dir, remote_dir):
        if not os.path.isdir(local_dir):
            return False
        # print("local_dir:", local_dir)
        local_names = os.listdir(local_dir)
        # print("list:", local_names)
        # print(remote_dir)
        self.ftp.cwd(remote_dir)
        for Local in local_names:
            src = os.path.join(local_dir, Local)
            if os.path.isdir(src):
                self.up_load_file_tree(src, Local)
            else:
                self.up_load_file(src, Local)
 
        self.ftp.cwd("..")
        return
 
    def down_load_file_tree(self, local_dir, remote_dir):
        print("remote_dir:", remote_dir)
        if not os.path.isdir(local_dir):
            os.makedirs(local_dir)
        self.ftp.cwd(remote_dir)
        remote_names = self.ftp.nlst()
        # print("remote_names", remote_names)
        # print(self.ftp.nlst(remote_dir))
        for file in remote_names:
            local = os.path.join(local_dir, file)
            if self.is_dir(file):
                self.down_load_file_tree(local, file)
            else:
                self.down_load_file(local, file)
        self.ftp.cwd("..")
        return
 
    def show(self, list):
        result = list.lower().split(" ")
        if self.path in result and "
" in result:
            self.bIsDir = True
 
    def is_dir(self, path):
        self.bIsDir = False
        self.path = path
        # this ues callback function ,that will change bIsDir value
        self.ftp.retrlines('LIST', self.show)
        return self.bIsDir
 
    def close(self):
        self.ftp.quit()
 
 
if __name__ == "__main__":
    ftp = myFtp('10.126.64.14',21)
    ftp.login("usr_esop", "PWD4ftp@201903#")
 
    ftp.down_load_file_tree(r"C:\PycharmProjects\untitled\backup", "/ZS_ESOP/55-548410/-/zh/Split"# ok
    ftp.up_load_file_tree(r"C:\PycharmProjects\untitled\backup", "/ZS_ESOP/55-548410/-/zh/Split"# ok
    ftp.close()
    print("ok!")

到此这篇关于Python网络编程之ftplib模块的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/springsnow/p/12120598.html

延伸 · 阅读

精彩推荐