Guest User

Untitled

a guest
Jun 21st, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.14 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. ## Copy files unattended over SSH using a glob pattern.
  4. ## Try first to connect using a private key from a private key file
  5. ## or from an SSH agent. If RSA authentication fails, then do
  6. ## a password login, provided it is allowed on the server.
  7.  
  8. hostname='127.0.0.1'
  9. port= 22
  10. username='paramikouser'
  11. password='paramikopassword'
  12. rsa_private_key=r"/home/paramikouser/.ssh/rsa_private_key"
  13.  
  14. dir_local='/home/paramikouser/local_data'
  15. dir_remote = "remote_machine_folder/subfolder"
  16. glob_pattern='*.xml'
  17.  
  18. import os
  19. import glob
  20. import paramiko
  21. import md5
  22.  
  23.  
  24. def agent_auth(transport, username):
  25. """
  26. Attempt to authenticate to the given transport using any of the private
  27. keys available from an SSH agent or from a local private file (assumes no pass phrase).
  28. """
  29. try:
  30. ki = paramiko.RSAKey.from_private_key_file(rsa_private_key)
  31. except Exception, e:
  32. print 'Failed loading' % (rsa_private_key, e)
  33.  
  34. agent = paramiko.Agent()
  35. agent_keys = agent.get_keys() + (ki,)
  36. if len(agent_keys) == 0:
  37. return
  38.  
  39. for key in agent_keys:
  40. print 'Trying ssh-agent key %s' % key.get_fingerprint(),
  41. try:
  42. transport.auth_publickey(username, key)
  43. print '... success!'
  44. return
  45. except paramiko.SSHException, e:
  46. print '... failed!', e
  47.  
  48.  
  49. # get host key, if we know one
  50. hostkeytype = None
  51. hostkey = None
  52. files_copied = 0
  53. try:
  54. host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
  55. except IOError:
  56. try:
  57. # try ~/ssh/ too, e.g. on windows
  58. host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts'))
  59. except IOError:
  60. print '*** Unable to open host keys file'
  61. host_keys = {}
  62.  
  63. if host_keys.has_key(hostname):
  64. hostkeytype = host_keys[hostname].keys()[0]
  65. hostkey = host_keys[hostname][hostkeytype]
  66. print 'Using host key of type %s' % hostkeytype
  67.  
  68. # now, connect and use paramiko Transport to negotiate SSH2 across the connection
  69. try:
  70. print 'Establishing SSH connection to:', hostname, port, '...'
  71. t = paramiko.Transport((hostname, port))
  72. t.start_client()
  73.  
  74. agent_auth(t, username)
  75.  
  76. if not t.is_authenticated():
  77. print 'RSA key auth failed! Trying password login...'
  78. t.connect(username=username, password=password, hostkey=hostkey)
  79. else:
  80. sftp = t.open_session()
  81. sftp = paramiko.SFTPClient.from_transport(t)
  82.  
  83. # dirlist on remote host
  84. # dirlist = sftp.listdir('.')
  85. # print "Dirlist:", dirlist
  86.  
  87. try:
  88. sftp.mkdir(dir_remote)
  89. except IOError, e:
  90. print '(assuming ', dir_remote, 'exists)', e
  91.  
  92. # print 'created ' + dir_remote +' on the hostname'
  93.  
  94. # BETTER: use the get() and put() methods
  95. # for fname in os.listdir(dir_local):
  96.  
  97. for fname in glob.glob(dir_local + glob_pattern):
  98. is_up_to_date = False
  99. if fname.lower().endswith('xml'):
  100. local_file = os.path.join(dir_local, fname)
  101. remote_file = dir_remote + '/' + os.path.basename(fname)
  102.  
  103. #if remote file exists, do MD5 comparison before copying
  104. if sftp.stat(remote_file):
  105. local_file_data = open(local_file, "rb").read()
  106. remote_file_data = sftp.open(remote_file).read()
  107. md1 = md5.new(local_file_data).digest()
  108. md2 = md5.new(remote_file_data).digest()
  109. if md1 == md2:
  110. is_up_to_date = True
  111. print "FILE IS UP TO DATE:", os.path.basename(fname)
  112. else:
  113. print "FILE NOT UP TO DATE:",
  114.  
  115. if not is_up_to_date:
  116. print 'Copying', local_file, 'to ', remote_file
  117. sftp.put(local_file, remote_file)
  118. files_copied += 1
  119.  
  120.  
  121. t.close()
  122.  
  123. except Exception, e:
  124. print '*** Caught exception: %s: %s' % (e.__class__, e)
  125. try:
  126. t.close()
  127. except:
  128. pass
  129. print '=' * 60
  130. print 'Total files copied:',files_copied
  131. print 'All operations complete! Press any key to exit...'
  132. print '=' * 60
Add Comment
Please, Sign In to add comment