1. #!/usr/bin/python
2. #coding=gbk
3. '''''
4. ftp自动下载、自动上传脚本,可以递归目录操作
5. '''
6.
7. from ftplib import FTP
8. import os,sys,string,datetime,time
9. import socket
10.
11. class MYFTP:
12. def __init__(self, hostaddr, username, password, remotedir, port=21):
13. self.hostaddr = hostaddr
14. self.username = username
15. self.password = password
16. self.remotedir = remotedir
17. self.port = port
18. self.ftp = FTP()
19. self.file_list = []
20. # self.ftp.set_debuglevel(2)
21. def __del__(self):
22. self.ftp.close()
23. # self.ftp.set_debuglevel(0)
24. def login(self):
25. ftp = self.ftp
26. try:
27. timeout = 60
28. socket.setdefaulttimeout(timeout)
29. ftp.set_pasv(True)
30. print '开始连接到 %s' %(self.hostaddr)
31. ftp.connect(self.hostaddr, self.port)
32. print '成功连接到 %s' %(self.hostaddr)
33. print '开始登录到 %s' %(self.hostaddr)
34. ftp.login(self.username, self.password)
35. print '成功登录到 %s' %(self.hostaddr)
36. debug_print(ftp.getwelcome())
37. except Exception:
38. deal_error("连接或登录失败")
39. try:
40. ftp.cwd(self.remotedir)
41. except(Exception):
42. deal_error('切换目录失败')
43.
44. def is_same_size(self, localfile, remotefile):
45. try:
46. remotefile_size = self.ftp.size(remotefile)
47. except:
48. remotefile_size = -1
49. try:
50. localfile_size = os.path.getsize(localfile)
51. except:
52. localfile_size = -1
53. debug_print('lo:%d re:%d' %(localfile_size, remotefile_size),)
54. if remotefile_size == localfile_size:
55. return 1
56. else:
57. return 0
58. def download_file(self, localfile, remotefile):
59. if self.is_same_size(localfile, remotefile):
60. debug_print('%s 文件大小相同,无需下载' %localfile)
61. return
62. else:
63. debug_print('>>>>>>>>>>>>下载文件 %s ... ...' %localfile)
64. #return
65. file_handler = open(localfile, 'wb')
66. self.ftp.retrbinary('RETR %s'%(remotefile), file_handler.write)
67. file_handler.close()
68.
69. def download_files(self, localdir='./', remotedir='./'):
70. try:
71. self.ftp.cwd(remotedir)
72. except:
73. debug_print('目录%s不存在,继续...' %remotedir)
74. return
75. if not os.path.isdir(localdir):
76. os.makedirs(localdir)
77. debug_print('切换至目录 %s' %self.ftp.pwd())
78. self.file_list = []
79. self.ftp.dir(self.get_file_list)
80. remotenames = self.file_list
81. #print(remotenames)
82. #return
83. for item in remotenames:
84. filetype = item[0]
85. filename = item[1]
86. local = os.path.join(localdir, filename)
87. if filetype == 'd':
88. self.download_files(local, filename)
89. elif filetype == '-':
90. self.download_file(local, filename)
91. self.ftp.cwd('..')
92. debug_print('返回上层目录 %s' %self.ftp.pwd())
93. def upload_file(self, localfile, remotefile):
94. if not os.path.isfile(localfile):
95. return
96. if self.is_same_size(localfile, remotefile):
97. debug_print('跳过[相等]: %s' %localfile)
98. return
99. file_handler = open(localfile, 'rb')
100. self.ftp.storbinary('STOR %s' %remotefile, file_handler)
101. file_handler.close()
102. debug_print('已传送: %s' %localfile)
103. def upload_files(self, localdir='./', remotedir = './'):
104. if not os.path.isdir(localdir):
105. return
106. localnames = os.listdir(localdir)
107. self.ftp.cwd(remotedir)
108. for item in localnames:
109. src = os.path.join(localdir, item)
110. if os.path.isdir(src):
111. try:
112. self.ftp.mkd(item)
113. except:
114. debug_print('目录已存在 %s' %item)
115. self.upload_files(src, item)
116. else:
117. self.upload_file(src, item)
118. self.ftp.cwd('..')
119.
120. def get_file_list(self, line):
121. ret_arr = []
122. file_arr = self.get_filename(line)
123. if file_arr[1] not in ['.', '..']:
124. self.file_list.append(file_arr)
125.
126. def get_filename(self, line):
127. pos = line.rfind(':')
128. while(line[pos] != ' '):
129. pos += 1
130. while(line[pos] == ' '):
131. pos += 1
132. file_arr = [line[0], line[pos:]]
133. return file_arr
134. def debug_print(s):
135. print (s)
136. def deal_error(e):
137. timenow = time.localtime()
138. datenow = time.strftime('%Y-%m-%d', timenow)
139. logstr = '%s 发生错误: %s' %(datenow, e)
140. debug_print(logstr)
141. file.write(logstr)
142. sys.exit()
143.
144. if __name__ == '__main__':
145. file = open("log.txt", "a")
146. timenow = time.localtime()
147. datenow = time.strftime('%Y-%m-%d', timenow)
148. logstr = datenow
149. # 配置如下变量
150. hostaddr = 'localhost' # ftp地址
151. username = 'test' # 用户名
152. password = 'test' # 密码
153. port = 21 # 端口号
154. rootdir_local = '.' + os.sep + 'bak/' # 本地目录
155. rootdir_remote = './' # 远程目录
156.
157. f = MYFTP(hostaddr, username, password, rootdir_remote, port)
158. f.login()
159. f.download_files(rootdir_local, rootdir_remote)
160.
161. timenow = time.localtime()
162. datenow = time.strftime('%Y-%m-%d', timenow)
163. logstr += " - %s 成功执行了备份\n" %datenow
164. debug_print(logstr)
165.
166. file.write(logstr)
167. file.close()
Python_实现ftp上传和下载
最新推荐文章于 2024-07-06 02:39:49 发布