Advertisement
Guest User

Untitled

a guest
Feb 2nd, 2017
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.04 KB | None | 0 0
  1. from abc import ABCMeta, abstractmethod
  2. import paramiko,telnetlib
  3. import logging,time
  4.  
  5. LOGGING_FORMAT = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'
  6. logger = logging.getLogger(__name__)
  7. logger.setLevel(logging.INFO)
  8. # create console handler and set level to debug
  9. ch = logging.StreamHandler()
  10. ch.setLevel(logging.DEBUG)
  11. # create formatter
  12. formatter = logging.Formatter(LOGGING_FORMAT)
  13. # add formatter to ch
  14. ch.setFormatter(formatter)
  15. # add ch to logger
  16. logger.addHandler(ch)
  17.  
  18. READ_TIMEOUT = 20
  19. READ_DELAY = 15
  20.  
  21.  
  22. class RemoteCommandExecutorAbstract():
  23. __metaclass__ = ABCMeta
  24.  
  25. def __init__(self, host, username, password):
  26. self.host = host
  27. self.username = username
  28. self.password = password
  29. self.connection = None
  30.  
  31. @abstractmethod
  32. def connect(self):
  33. ''' This should be called before executing any command.
  34. It returns the connection Object'''
  35. pass
  36.  
  37. @abstractmethod
  38. def connected(self):
  39. '''Returns true if the connection is active'''
  40. pass
  41.  
  42. @abstractmethod
  43. def disconnect(self):
  44. pass
  45.  
  46. @abstractmethod
  47. def execute_cmd(self,command):
  48. '''This returns the command output'''
  49. pass
  50.  
  51.  
  52. class SSHCommandExecutor(RemoteCommandExecutorAbstract):
  53. def connect(self):
  54. ssh = paramiko.SSHClient()
  55. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  56. try:
  57. print "connecting to %s......" % self.host
  58. ssh.connect(self.host, username=self.username, password=self.password)
  59. print "connected to %s" % self.host
  60. self.connection = ssh
  61. except Exception, e:
  62. print "Failed to connect to %s: %s" % (self.host, e)
  63. return self
  64.  
  65. def disconnect(self):
  66. try:
  67. self.connection.close()
  68. except Exception, e:
  69. print "Failed to close the ssh connection: %s" % e
  70. return False
  71. return True
  72.  
  73. def connected(self):
  74. return self.connection != None
  75.  
  76. def execute_cmd(self, cmd):
  77. if not self.connected():
  78. print "Connection to %s has not been established. Cannot execute any command"
  79. return None
  80. stdin, stdout, stderr = self.connection.exec_command(cmd)
  81. return stdout.read()
  82.  
  83.  
  84. class TelnetCommandExecutor(RemoteCommandExecutorAbstract):
  85. def connect(self):
  86. try:
  87. print "connecting to %s......" % self.host
  88. tn = telnetlib.Telnet(self.host)
  89. tn.read_until("login:", READ_TIMEOUT)
  90. tn.write(self.username + "\n")
  91. tn.read_until("password:", READ_TIMEOUT)
  92. tn.write(self.password + "\n")
  93. print "connected to %s" % self.host
  94. self.connection = tn
  95. time.sleep(READ_DELAY)
  96. self.connection.read_very_eager()
  97. except Exception, e:
  98. print "Failed to connect to %s: %s" % (self.host, e)
  99. return self
  100.  
  101. def disconnect(self):
  102. try:
  103. self.connection.close()
  104. except Exception, e:
  105. print "Failed to close the ssh connection: %s" % e
  106. return False
  107. return True
  108.  
  109. def connected(self):
  110. return self.connection != None
  111.  
  112. def execute_cmd(self, cmd):
  113. def readOutput(afterSeconds=READ_DELAY):
  114. logger.debug("<--Reading device's output")
  115. time.sleep(afterSeconds)
  116. output = self.connection.read_very_eager().strip()
  117. logger.debug("-------------:\n %s\n-------------" % output)
  118. return output
  119.  
  120. if not self.connected():
  121. print "Connection to %s has not been established. Cannot execute any command"
  122. return None
  123. cmd = cmd.strip()
  124. logger.debug("-->Sending command: %s" % cmd)
  125. self.connection.write("\n%s\n" % cmd)
  126. output = readOutput()
  127. if "Error:"in output:
  128. raise RuntimeError("%s command has failed with %s" % (cmd, output))
  129. return output
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement