class SerialConnection(ConnectionType): def __init__(self, device='/dev/ttyACM0', baudRate=115200, recvTimeout=20): self.logger = RamaLogger().getLogger() self.device = device self.baudRate = baudRate self.recvTimeout = recvTimeout self.Connect() def Connect(self): self.logger.info("Connecting to %s" % self.device) self.server = serial.Serial(self.device, self.baudRate, timeout=self.recvTimeout) self.logger.info("Already connect to %s" % self.device) def Send(self, cmd): self.logger.debug('Commnad: ' + str(cmd)) self.server.write(cmd) def Receive(self, response_length): response = self.server.read(response_length) return response def Disconnect(self): '''Disconnect to target device.''' self.server.close() self.server = None self.logger.info('Serial connection is closed.')
class SocketConnection(ConnectionType): def __init__(self, host, port, recvTimeout=50): self.logger = RamaLogger().getLogger() self.recvTimeout = recvTimeout self.host = host self.port = port '''OpenSocket''' self.Connect() @retry(Exception) def Connect(self): self.logger.info("Connecting to %s:%s" % (self.host,self.port)) self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server.settimeout(self.recvTimeout) self.server.connect((self.host,self.port)) self.logger.info("Already connect to %s:%s" % (self.host,self.port)) def Send(self, cmd): self.logger.debug('Commnad: ' + str(cmd)) self.server.sendall(cmd) def Receive(self, response_length): response = self.server.recv(response_length) self.logger.info("Raw Data:") self.logger.info(response) return response def Disconnect(self): '''Disconnect to target device.''' self.server.close() self.server = None self.logger.info('Socket is Closed.')
class ParentCommand: def __init__(self): self.logger = RamaLogger().getLogger() # SendCommand---------------------------------------------------------- # Command Header # Unused (32 bits) Internal use only, set to zeroes self.SendUnused = 0 # The Version is 1 self.SendVersion = 1 # Default self.SendGroupid = 2 self.SendCmdid = 3 self.SendPaylen = 4 # Command pack format, depend on Command Payload self.SendCmdHeaderFormat = "<5I" self.SendCmdPayloadFormat = "" self.SendCommand = "" # ReceiveResponse---------------------------------------------------------- # Response unpack format, depend on command-specific response payload self.ResponsePayloadFormat = "" self.ResponseHeaderFormat = "<5II1024s" # Default self.RecvUnused = 0 self.RecvGroupid = 0 self.RecvCmdid = 0 self.RecvVersion = 0 self.RecvPaylen = 0 self.ResultCode = 0 self.ResultMsg = "" ####################################################### def PackCommand(self): # Pack Command Header to SendCommand. self.SendCommand = pack(self.SendCmdHeaderFormat, self.SendUnused, self.SendCmdid, self.SendGroupid, self.SendVersion, self.SendPaylen) return self.SendCommand def UnpackResponse(self, Response): # Unpack Response Header and store in every field. self.RecvUnused, self.RecvCmdid,\ self.RecvGroupid, self.RecvVersion,\ self.RecvPaylen, self.ResultCode,\ self.ResultMsg = unpack_from( self.ResponseHeaderFormat, Response, offset=0) self.ResultMsg = self.ResultMsg.decode().rstrip('\x00') return self.RecvUnused, self.RecvCmdid, self.RecvGroupid, self.RecvVersion,\ self.RecvPaylen def ReturnCheck(self): return self.ResultCode, self.ResultMsg def STDOut(self): # Print out every fields individually. # Note: Need to decode content, if the type of field is char as ResultMsg. self.logger.debug("UNUSED: " + str(self.RecvUnused)) self.logger.debug("CMDID: " + str(self.RecvCmdid)) self.logger.debug("GRPID: " + str(self.RecvGroupid)) self.logger.debug("VSION: " + str(self.RecvVersion)) self.logger.debug("GRPID: " + str(self.RecvGroupid)) self.logger.debug("PAYLEN: " + str(self.RecvPaylen)) self.logger.info("ResultCode: " + str(self.ResultCode)) self.logger.info("ResultMsg: " + repr(self.ResultMsg))
class SSHConnection(ConnectionType): def __init__(self, host, username, password): self.logger = RamaLogger().getLogger() self.host_stingray = host self.username_stingray = username self.password_stingray = password self.timeout = Config.get('SSHClient', 'timeout') '''Connect SSH''' self.Connect() @retry(Exception) def Connect(self): "Login to the remote server" self.logger.info('Connectingt to %s:%s' % (self.host, self.port)) try: self.client = paramiko.SSHClient() self.client.load_system_host_keys() self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.client.connect(hostname=self.host_stringray, port=22, username=self.username_stingray, password=self.password_stingray, timeout=self.timeout, allow_agent=False, look_for_keys=False) self.logger.info("Connected to the server", self.host) except paramiko.AuthenticationException: self.logger.warning( "Authentication failed, please verify your credentials") except paramiko.SSHException as sshException: self.logger.error("Could not establish SSH connection: %s" % sshException) except socket.timeout as e: self.logger.error("Connection timed out: %s" % e) except Exception as e: self.logger.error("Exception in connecting to the server: %s" % e) def Send(self, command): """Execute a command on the remote host.Return a tuple containing an integer status and a two strings, the first containing stdout and the second containing stderr from the command.""" self.logger.info("Executing command --> {}".format(command)) try: stdin, stdout, stderr = self.client.exec_command(command, timeout=10) self.ssh_output = stdout.read() self.ssh_error = stderr.read() except paramiko.SSHException: self.logger.debug("Failed to execute the command!", command) def Receive(self): '''Receive result from remote server''' self.logger.info(self.ssh_output) self.logger.info(self.ssh_error) return self.ssh_output, self.ssh_error def Disconnect(self): '''Close SSH client''' self.client.close() self.client = None self.logger.info('SSH is Closed.')