class RemoteExecutor: """ Execute a command to the remote host through ssh session. This function also starts three threads that handle the input, error and output streams. Then the other functions can be used for conversating with the process. remexecutor.exec('ls -al') # prints remote home directory contents """ def __init__(self, remotehost): """ Initialize the connection.""" self.__connection = remotehost.connection self.__env = remotehost.env self.__session = self.__connection.openSession() self.__instr = None self.__errstr = None self.__inputreader = None self.__errortreader = None self.__outputwriter = None def exec(self,command): if not self.__connection.isAuthenticationComplete(): print "Connection not established" return if self.__session == None: self.__session = self.__connection.openSession() sess = self.__session if type(command) is type([]): # if command is a list make it a string command = " ".join(command) # make environment variables to string and assemble command environment = " ".join(["=".join(i) for i in self.__env]) command = "export " + environment + " && " + command sess.execCommand(command) # execute command self.__outputwriter = DataOutputStream(sess.getStdin()) # start a new thread for the input stream of the process and set the # Reader self.__instr = StreamGobbler(sess.getStdout()) self.__inputreader = Reader(BufferedReader(InputStreamReader(self.__instr))) # start a new thread for error stream of the process and set the # Reader self.__errstr = StreamGobbler(sess.getStderr()) self.__errorreader = Reader(BufferedReader(InputStreamReader(self.__errstr))) def input(self): """ Function for reading the output of a process. Wrapper for Reader readString function. """ if self.__inputreader is None: print "Error __inputstreamer__ is None" return return self.__inputreader.readString() def error(self): """ Function for reading the error of a process. Wrapper for Reader readString function. """ if self.__errorreader is None: print "Error __errorstreamer__ is None" return return self.__errorreader.readString() def write(self, bytes = None): """ Function to read from system in and write to the process input (or the proc output) """ writer = self.__outputwriter if bytes is None: bytes = raw_input() #for i in bytes[:]: # print ord(i) writer.writeBytes(bytes+"\n") writer.flush() def getEnv(self, var): env = self.__env for i in env: if var in i: return i[1] def setEnv(self, var, value): env = self.__env curvar = None for i in range(len(env)): if var in env[i]: curvar = env[i][1] del env[i] break self.__env.append((var,value)) def close(self): self.__instr.close() self.__errstr.close() self.__session.close() self.__instr = None self.__errstr = None self.__session = None