具體代碼如下所示:
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
|
#!/usr/bin/python # coding=utf-8 import time import os def __ftp_upload(ftp,local,remote,isDel = False ): if os.path.isdir(local): for f in os.listdir(local): if os.path.isdir(local + f): try : ftp.cwd(remote + f) except : ftp.mkd(remote + f) print local + f __ftp_upload(ftp,local + f + '/' ,remote + f + '/' ,isDel) else : print remote + f print local + f fp = open (local + f, 'rb' ) ftp.storbinary( 'STOR ' + remote + f, fp, 4096 ) fp.close() if (isDel = = True ): os.remove(local) else : fp = open (local + f, 'rb' ) ftp.storbinary( 'STOR ' + remote + f, fp, 4096 ) fp.close() if (isDel = = True ): os.remove(local) def ftp_upload(host,port,username,password,local,remote,isDel = False ): ftp = FTP() try : ftp.connect(host,port) ftp.login(username,password) except : return False try : __ftp_upload(ftp,local,remote, False ) except Exception,e: print e ftp.close() return True def ftp_download(host,port,username,password,local,remote): ftp = FTP() ftp.connect(host,port) ftp.login(username,password) ret = False try : if os.path.isdir(local): for f in ftp. dir (remote): fp = open (local + f, 'wb' ) ftp.retrbinary( 'RETR ' + remote + f, fp.write, 4096 ) fp.close() else : fp = open (local, 'wb' ) ftp.retrbinary( 'RETR ' + remote, fp.write, 4096 ) fp.close() ret = True except Exception,e: print ( "download exception:\n" ,e) ftp.close() return ret if __name__ = = '__main__' : host = '*.*.*.*' port = '21' username = 'xxx' password = 'xxx' ftp_upload(host,port,username,password, '/home/pi/work/xx/' , '/home/ubuntu/xx/' , False ) print 'download' ftp_download(host,port,username,password, '/home/pi/work/xx/hh.txt' , '/home/ubuntu/xx/hh.txt' ) |
只完成了按目錄結(jié)構(gòu)上傳,下載還沒(méi)弄好。
補(bǔ)充:下面看下Python ftp 上傳和下載
工具
python3
ftplib
上傳
1
2
3
4
5
6
7
8
|
from ftplib import FTP ftp = FTP(host = '127.0.0.1' , user = 'test' , passwd = 'test' ) #創(chuàng)建 ftp.cwd( '/home/test/ftp/' ) #上傳路徑 fd = open ( 'test.txt' , 'rb' ) #以只讀的方式打開(kāi)要上傳的文件 ftp.storbinary( 'STOR test.txt' , fd) #上傳文件 fd.close() ftp.quit() #退出登錄 ftp.close() #關(guān)閉連接 |
下載
1
2
3
4
5
6
7
8
|
from ftplib import FTP ftp = FTP(host = '127.0.0.1' , user = 'test' , passwd = 'test' ) #創(chuàng)建 ftp.cwd( '/home/test/ftp/' ) #服務(wù)器下載路徑 fd = open ( 'test.txt' , 'wb' ) #以只寫(xiě)的方式打開(kāi)要下載的文件 ftp.retrbinary( 'RETR test.txt' , fd.write, 2048 ) #下載文件 fd.close() ftp.quit() #退出登錄 ftp.close() #關(guān)閉連接 |
總結(jié)
以上所述是小編給大家介紹的jpython ftp 按目錄結(jié)構(gòu)上傳下載的實(shí)現(xiàn)代碼,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)服務(wù)器之家網(wǎng)站的支持!
原文鏈接:https://blog.csdn.net/liudijiang/article/details/82655957