Advertisement
Guest User

Untitled

a guest
Mar 20th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.86 KB | None | 0 0
  1. from ftplib import FTP
  2. import os
  3. import sys
  4. import time
  5. import socket
  6.  
  7. # 本地日志存储路径
  8. local_log_path = "log.txt"
  9.  
  10.  
  11. class FtpUtil(object):
  12. def __init__(self, host, port):
  13. '''
  14. 初始化ftp参数
  15. :param host:
  16. :param port:
  17. '''
  18. self.host = host
  19. self.port = port
  20. self.ftp = FTP()
  21. self.ftp.encoding = 'utf-8'
  22. self.log_file = open(local_log_path, "a")
  23. self.file_list = []
  24. self.ftp.set_pasv(False)
  25.  
  26. def login(self, username, password):
  27. '''
  28. 登录ftp
  29. :param username:
  30. :param password:
  31. :return:
  32. '''
  33. try:
  34. timeout = 60
  35. socket.setdefaulttimeout(timeout)
  36. # 0主动模式 1 #被动模式
  37. self.ftp.set_pasv(1)
  38. # 打开调试级别2,显示详细信息
  39. self.ftp.set_debuglevel(2)
  40. print('开始连接到 %s' % self.host)
  41. self.ftp.connect(self.host, self.port)
  42. print('成功连接到 %s' % self.host)
  43. print('开始登录到 %s' % self.host)
  44. self.ftp.login(username, password)
  45. print('成功登录到 %s' % self.host)
  46. print(self.ftp.welcome)
  47. except Exception as err:
  48. self.deal_error("ftp 连接或登录失败 ,错误描述为:%s " % err)
  49. print("ftp 连接或登录失败 ,错误描述为:%s " % err)
  50. pass
  51.  
  52. def _try_cwd(self, item):
  53. '''
  54. 测试ftp文件夹是否存在
  55. :param item:
  56. :return:
  57. '''
  58. try:
  59. self.ftp.cwd(item)
  60. return True
  61. except Exception:
  62. return False
  63.  
  64. def download_file(self, local_file, remote_path, remote_file):
  65. '''
  66. 从ftp下载文件
  67. :param local_file:
  68. :param remote_file:
  69. :return:
  70. '''
  71. self.debug_print("download_file()---> local_path = %s ,remote_path = %s" % (local_file, remote_file))
  72. try:
  73. self.debug_print('>>>>>>>>>>>>下载文件 %s ... ...' % local_file)
  74. self.ftp.cwd(remote_path)
  75. with open(local_file, 'wb') as f:
  76. self.ftp.retrbinary('RETR {0}'.format(remote_file), f.write)
  77. except Exception as err:
  78. self.debug_print('下载文件出错,出现异常:%s ' % err)
  79. return
  80.  
  81. def download_file_tree(self, local_path, remote_path):
  82. '''
  83. 从远程目录下载多个文件到本地目录
  84. :param local_path:
  85. :param remote_path:
  86. :return:
  87. '''
  88. print("download_file_tree()---> local_path = %s ,remote_path = %s" % (local_path, remote_path))
  89. try:
  90. self.ftp.cwd(remote_path)
  91. except Exception as err:
  92. self.debug_print('远程目录%s不存在,继续...' % remote_path + " ,具体错误描述为:%s" % err)
  93. return
  94.  
  95. if not os.path.isdir(local_path):
  96. self.debug_print('本地目录%s不存在,先创建本地目录' % local_path)
  97. os.makedirs(local_path)
  98.  
  99. self.debug_print('切换至目录: %s' % self.ftp.pwd())
  100. self.file_list = []
  101. # 方法回调
  102. self.ftp.dir(self.get_file_list)
  103.  
  104. remote_names = self.file_list
  105. self.debug_print('远程目录 列表: %s' % remote_names)
  106. for item in remote_names:
  107. file_type = item[0]
  108. file_name = item[1]
  109. local = os.path.join(local_path, file_name)
  110. if file_type == 'd':
  111. print("download_file_tree()---> 下载目录: %s" % file_name)
  112. self.download_file_tree(local, file_name)
  113. elif file_type == '-':
  114. print("download_file()---> 下载文件: %s" % file_name)
  115. self.download_file(local, file_name)
  116. self.ftp.cwd("..")
  117. self.debug_print('返回上层目录 %s' % self.ftp.pwd())
  118. return True
  119.  
  120. def upload_file(self, local_file, remote_path):
  121. '''
  122. 从本地上传文件到ftp
  123. :param local_file: 本地文件
  124. :param remote_path: 远程路径
  125. :return:
  126. '''
  127. try:
  128. if not self._try_cwd(remote_path):
  129. self.ftp.mkd(remote_path)
  130. self.ftp.cwd(remote_path)
  131. if not os.path.isdir(local_file):
  132. self.ftp.storbinary("STOR {0}".format(os.path.basename(local_file)), open(local_file, "rb"))
  133. size = os.path.getsize(local_file)
  134. self.debug_print('上传: %s' % local_file + " 成功!文件大小: " + str(size) + " Bytes.")
  135. else:
  136. print('%s 不是文件' % local_file)
  137. return
  138. except Exception as err:
  139. self.debug_print('上传失败,继续...' % remote_path + " ,具体错误描述为:%s" % err)
  140. return
  141.  
  142. def upload_All_file(self, local_path, remote_path):
  143. '''
  144. 从本地上传指定文件夹下的所有文件到ftp
  145. :param local_path:
  146. :param remote_path:
  147. :return:
  148. '''
  149. if len(os.listdir(local_path)) == 0:
  150. self.debug_print("指定的目录不存在或为空:%s" % local_path)
  151. print("指定的目录不存在或为空:%s" % local_path)
  152. else:
  153. for files in os.listdir(local_path):
  154. self.upload_file(local_path + "/" + files, remote_path + '/')
  155.  
  156. def close(self):
  157. '''
  158. 退出ftp
  159. :return:
  160. '''
  161. print("close()---> FTP退出")
  162. self.ftp.quit()
  163. self.log_file.close()
  164.  
  165. def debug_print(self, s):
  166. '''
  167. 打印日志
  168. :param s:
  169. :return:
  170. '''
  171. self.write_log(s)
  172.  
  173. def deal_error(self, e):
  174. '''
  175. 处理错误异常
  176. :param e:
  177. :return:
  178. '''
  179. log_str = '发生错误: %s' % e
  180. self.write_log(log_str)
  181. sys.exit()
  182.  
  183. def write_log(self, log_str):
  184. '''
  185. 记录日志
  186. :param log_str:
  187. :return:
  188. '''
  189. time_now = time.localtime()
  190. date_now = time.strftime('%Y-%m-%d %H:%M:%S', time_now)
  191. format_log_str = "%s ---> %s \r\n" % (date_now, log_str)
  192. print(format_log_str)
  193. self.log_file.write(format_log_str)
  194.  
  195. def get_file_list(self, line):
  196. '''
  197. 获取文件列表
  198. :param line:
  199. :return:
  200. '''
  201. file_arr = self.get_file_name(line)
  202. # 去除 . 和 ..
  203. if file_arr[1] not in ['.', '..']:
  204. self.file_list.append(file_arr)
  205.  
  206. def get_file_name(self, line):
  207. '''
  208. 获取文件名
  209. :param line:
  210. :return:
  211. '''
  212. pos = line.rfind(':')
  213. while (line[pos] != ' '):
  214. pos += 1
  215. while (line[pos] == ' '):
  216. pos += 1
  217. file_arr = [line[0], line[pos:]]
  218. return file_arr
  219.  
  220.  
  221. def ftp_dirs_exists(self, root_path, dir_name):
  222. '''
  223. 判断ftp服务器上是否存在指定的文件夹,不存在则创建
  224. :param root_path:
  225. :param dir_name:
  226. :return:
  227. '''
  228. ftplist = self.ftp.nlst(root_path)
  229. real_path_dir = root_path + "/" + dir_name
  230. # 判断该路径地址下是否存在文件夹,若不存在则创建指定格式的文件夹
  231. if len(ftplist) == 0:
  232. self.ftp.mkd(real_path_dir)
  233. else:
  234. # 遍历指定路径下非空文件夹下的所有文件信息
  235. for dirs_name in ftplist:
  236. # 如果指定路径下的文件夹信息和规定的文件夹信息一致,则不操作
  237. if dirs_name == dir_name:
  238. return
  239. else:
  240. # 否则创建规定的文件夹
  241. self.ftp.mkd(real_path_dir)
  242.  
  243.  
  244. if __name__ == '__main__':
  245. my_ftp = FtpUtil('localhost', 21)
  246. my_ftp.login("xxxx", "xxxx")
  247. my_ftp.upload_file('E:\\test\\xxxx.png', '/media/test')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement