1 import ftplib,os
2 temp=os.environ["temp"]
3 #参考连接:https://blog.csdn.net/wyt2wyt/article/details/128951039
4 ftp = ftplib.FTP()
5 ftp.connect("127.0.0.1",2121)
6 ftp.login("user","123456789")
7
8 def upload(f, remote_path, local_path): #上传
9 fp = open(local_path, "rb")
10 buf_size = 1024
11 f.storbinary("STOR {}".format(remote_path), fp, buf_size)
12 fp.close()
13 def download(f, remote_path, local_path): #下载
14 fp = open(local_path, "wb")
15 buf_size = 1024
16 f.retrbinary('RETR {}'.format(remote_path), fp.write, buf_size)
17 fp.close()
18 def quit(f): #退出连接
19 f.quit()
20 def typefile(f,file): #读取服务器文件,但不下载
21 local_path=temp+"/TEMPfile"
22 fp = open(local_path, "wb")
23 buf_size = 1024
24 f.retrbinary('RETR {}'.format(file), fp.write, buf_size)
25 fp.close()
26 f=open(local_path,"r",encoding="UTF-8")
27 get=f.read()
28 f.close()
29 os.remove(local_path)
30 #return get
31 print(get)
32 def nlst(ft,cwd=""): #获取当前目录的所有文件
33 try:
34 ft.nlst(cwd)
35 except:
36 return []
37 #return ft.nlst(cwd)
38 print(ft.nlst(cwd))
39 def DownLoadFileTree(ft, LocalDir, RemoteDir): #下载一个目录
40 def DownLoadFile(ft, LocalFile, RemoteFile): # 下载单个文件
41 file_handler = open(LocalFile, 'wb')
42 ft.retrbinary('RETR ' + RemoteFile, file_handler.write)
43 file_handler.close()
44 return True
45 if not os.path.exists(LocalDir):
46 os.makedirs(LocalDir)
47 ft.cwd(RemoteDir)
48 RemoteNames = ft.nlst()
49 for file in RemoteNames:
50 Local = os.path.join(LocalDir, file)
51 if file.find(".") == -1:
52 if not os.path.exists(Local):
53 os.makedirs(Local)
54 DownLoadFileTree(ft,Local, file)
55 else:
56 DownLoadFile(ft,Local, file)
57 ft.cwd("..")
58 return
59 #upload(ftp,r"\FTP-Server.py",r"D:\cnblogs\python脚本\FTP-Server.py")
60 #download(ftp,r"\FTP-Server.py",r"D:\FTP-Server.py")
61 #typefile(ftp,r"\temp\donfag_mysql_info.txt")
62 #nlst(ftp,cwd=r"\temp")
63 #DownLoadFileTree(ftp,r"e:\temp\temp",r"\temp")