Advertisement
Guest User

Untitled

a guest
May 24th, 2018
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.94 KB | None | 0 0
  1. import paramiko
  2. import os
  3.  
  4.  
  5. def find_file(file_list, search_file):
  6. for remoteFile in file_list:
  7. if remoteFile.filename == search_file:
  8. return remoteFile
  9. return None
  10.  
  11.  
  12. def is_ignored(ignored_extenions, extension):
  13. for ignored_extension in ignored_extenions:
  14. if ignored_extension == extension:
  15. return True
  16. return False
  17.  
  18.  
  19. class FileSender:
  20. def __init__(self, mode, ignored_extensions):
  21. self.mode = mode
  22. self.ssh = None
  23. self.sftp = None
  24. self.socket = None
  25. self.ignored_extensions = ignored_extensions
  26.  
  27.  
  28. def connect(self, username, password, hostname, port):
  29. self.ssh = paramiko.Transport(hostname, port)
  30. self.ssh.connect(username=username, password=password)
  31. self.sftp = paramiko.SFTP.from_transport(self.ssh)
  32.  
  33. def synchronize(self, local_path, remote_path):
  34. sent = []
  35. remote_folder = self.sftp.listdir_attr(remote_path)
  36. local_folder = [file for file in os.listdir(local_path) if os.path.isfile(os.path.join(local_path, file))] #generator expressions
  37.  
  38. for localFile in local_folder:
  39. filename, file_extension = os.path.splitext(localFile)
  40. #print(filename + file_extension)
  41. if is_ignored(self.ignored_extensions, file_extension):
  42. continue
  43. if self.mode == "override":
  44. local_file_path = os.path.join(local_path, localFile)
  45. #print(local_file_path)
  46. remote_file_path = remote_path + "/" + localFile
  47. self.sftp.put(local_file_path,remote_file_path)
  48. sent.append(localFile)
  49. elif self.mode == "update":
  50. remote_file = find_file(remote_folder, localFile)
  51. if remote_file is None:
  52. continue
  53. else:
  54. file_stat = os.stat(os.path.join(local_path, localFile))
  55. if file_stat.st_mtime > remote_file.st_mtime:
  56. local_file_path = os.path.join(local_path, localFile)
  57. remote_file_path = remote_path + "/" + localFile
  58. self.sftp.put(local_file_path, remote_file_path)
  59. sent.append(localFile)
  60. else:
  61. continue
  62.  
  63. elif self.mode == "add_non_existing":
  64. remote_file = find_file(remote_folder, localFile)
  65. if remote_file is None:
  66. local_file_path = os.path.join(local_path, localFile)
  67. remote_file_path = remote_path + "/" + localFile
  68. self.sftp.put(local_file_path, remote_file_path)
  69. sent.append(localFile)
  70. else:
  71. continue
  72. for file in sent:
  73. print(file)
  74.  
  75. def disonnect(self):
  76. self.sftp.close()
  77. self.ssh.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement