Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from abc import ABCMeta, abstractmethod
- import paramiko,telnetlib
- import logging,time
- LOGGING_FORMAT = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'
- logger = logging.getLogger(__name__)
- logger.setLevel(logging.INFO)
- # create console handler and set level to debug
- ch = logging.StreamHandler()
- ch.setLevel(logging.DEBUG)
- # create formatter
- formatter = logging.Formatter(LOGGING_FORMAT)
- # add formatter to ch
- ch.setFormatter(formatter)
- # add ch to logger
- logger.addHandler(ch)
- READ_TIMEOUT = 20
- READ_DELAY = 15
- class RemoteCommandExecutorAbstract():
- __metaclass__ = ABCMeta
- def __init__(self, host, username, password):
- self.host = host
- self.username = username
- self.password = password
- self.connection = None
- @abstractmethod
- def connect(self):
- ''' This should be called before executing any command.
- It returns the connection Object'''
- pass
- @abstractmethod
- def connected(self):
- '''Returns true if the connection is active'''
- pass
- @abstractmethod
- def disconnect(self):
- pass
- @abstractmethod
- def execute_cmd(self,command):
- '''This returns the command output'''
- pass
- class SSHCommandExecutor(RemoteCommandExecutorAbstract):
- def connect(self):
- ssh = paramiko.SSHClient()
- ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
- try:
- print "connecting to %s......" % self.host
- ssh.connect(self.host, username=self.username, password=self.password)
- print "connected to %s" % self.host
- self.connection = ssh
- except Exception, e:
- print "Failed to connect to %s: %s" % (self.host, e)
- return self
- def disconnect(self):
- try:
- self.connection.close()
- except Exception, e:
- print "Failed to close the ssh connection: %s" % e
- return False
- return True
- def connected(self):
- return self.connection != None
- def execute_cmd(self, cmd):
- if not self.connected():
- print "Connection to %s has not been established. Cannot execute any command"
- return None
- stdin, stdout, stderr = self.connection.exec_command(cmd)
- return stdout.read()
- class TelnetCommandExecutor(RemoteCommandExecutorAbstract):
- def connect(self):
- try:
- print "connecting to %s......" % self.host
- tn = telnetlib.Telnet(self.host)
- tn.read_until("login:", READ_TIMEOUT)
- tn.write(self.username + "\n")
- tn.read_until("password:", READ_TIMEOUT)
- tn.write(self.password + "\n")
- print "connected to %s" % self.host
- self.connection = tn
- time.sleep(READ_DELAY)
- self.connection.read_very_eager()
- except Exception, e:
- print "Failed to connect to %s: %s" % (self.host, e)
- return self
- def disconnect(self):
- try:
- self.connection.close()
- except Exception, e:
- print "Failed to close the ssh connection: %s" % e
- return False
- return True
- def connected(self):
- return self.connection != None
- def execute_cmd(self, cmd):
- def readOutput(afterSeconds=READ_DELAY):
- logger.debug("<--Reading device's output")
- time.sleep(afterSeconds)
- output = self.connection.read_very_eager().strip()
- logger.debug("-------------:\n %s\n-------------" % output)
- return output
- if not self.connected():
- print "Connection to %s has not been established. Cannot execute any command"
- return None
- cmd = cmd.strip()
- logger.debug("-->Sending command: %s" % cmd)
- self.connection.write("\n%s\n" % cmd)
- output = readOutput()
- if "Error:"in output:
- raise RuntimeError("%s command has failed with %s" % (cmd, output))
- return output
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement