Guest User

Untitled

a guest
Apr 22nd, 2018
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.60 KB | None | 0 0
  1. #!/usr/bin/env python2.7
  2. # -*- coding: UTF-8 -*-
  3. # File: ScpWrapper
  4. #
  5. __author__ = 'Costas Tyfoxylos <costas.tyf@gmail.com>'
  6. __docformat__ = 'plaintext'
  7. __date__ = '2015-03-17'
  8.  
  9. import os
  10. import sys
  11. import sh
  12. import logging
  13.  
  14. reload(sys)
  15.  
  16. logger_basename = 'ScpWrapper'
  17. logger = logging.getLogger(logger_basename)
  18. ch = logging.StreamHandler()
  19. ch.setLevel(logging.INFO)
  20. # create formatter
  21. log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
  22. formatter = logging.Formatter(log_format)
  23. # add formatter to ch
  24. ch.setFormatter(formatter)
  25. # add ch to logger
  26. logger.addHandler(ch)
  27. logger.setLevel(logging.INFO)
  28.  
  29.  
  30. class ScpWrapper(object):
  31. def __init__(self, user_name, server, key):
  32. # open stdout in unbuffered mode
  33. sys.stdout = os.fdopen(sys.stdout.fileno(), 'wb', 0)
  34. self.user_name = user_name
  35. self.server = server
  36. self.key = self._validate_key(key)
  37. self._aggregated = ''
  38. self._authenticate()
  39. self._scp = sh.scp.bake('-i', self.key,
  40. '-o', 'StrictHostKeyChecking=no')
  41. self._connection = '{user}@{target}'.format(user=self.user_name,
  42. target=self.server)
  43.  
  44. @staticmethod
  45. def _validate_key(key):
  46. try:
  47. _ = open(key).read()
  48. except IOError:
  49. message = 'Unable to read key file. Cannot continue...'
  50. logger.error(message)
  51. raise SystemExit(message)
  52. return key
  53.  
  54. def _check_login(self, char, stdin, process):
  55. self._aggregated += char
  56. if self._aggregated.endswith(
  57. 'password: ') or self._aggregated.endswith("': "):
  58. # reinstate the normal buffered mode for stdout
  59. reload(sys)
  60. process.kill()
  61.  
  62. def _authenticate(self):
  63. try:
  64. logger.info('Checking key access')
  65. _ = sh.ssh('-o', 'IdentitiesOnly=yes',
  66. '-o', 'IdentityFile={key}'.format(key=self.key),
  67. '{user}@{server}'.format(user=self.user_name,
  68. server=self.server),
  69. 'ls',
  70. _out=self._check_login,
  71. _out_bufsize=0,
  72. _tty_in=True)
  73. # reinstate the normal buffered mode for stdout
  74. except sh.SignalException_9:
  75. logger.error('Failed!')
  76. message = "User doesn't have key access to the server."
  77. logger.error(message)
  78. raise SystemExit(message)
  79. except sh.ErrorReturnCode_255:
  80. message = 'Could not connect to ssh server :{server}.'.format(
  81. server=self.server)
  82. logger.exception(message)
  83. raise SystemExit(message)
  84. return True
  85.  
  86. def copy(self, source, destination):
  87. destination = destination[:-1] if destination.endswith('/') else destination
  88. try:
  89. destination = '{connection}:{destination}'.format(connection=self._connection,
  90. destination=destination)
  91. logger.info('Trying to copy {source} to {destination}'.format(source=source,
  92. destination=destination))
  93. self._scp(source, destination)
  94. logger.info('Done')
  95. result = True
  96. except Exception:
  97. message = 'Failed to copy {source} to {destination}.'.format(
  98. source=source,
  99. destination=destination)
  100. logger.exception(message)
  101. result = False
  102. return result
Add Comment
Please, Sign In to add comment