Example #1
0
    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)))
Example #2
0
    def exec(self,command):
        """ Execute an OS command. This function also starts three threads 
        that handle the input, error and output streams. Then the other 
        functions can be used to make a conversation with the os process."""
        rt = Runtime.getRuntime()
        proc = rt.exec(command)

        self.__outputwriter = DataOutputStream(proc.getOutputStream())
            
        # start a new thread for the input stream of the process and set the
        # Reader
        self.__instr = StreamGobbler(proc.getInputStream())
        self.__inputreader = Reader(BufferedReader(InputStreamReader(self.__instr)))

        # start a new thread for error stream of the process and set the 
        # Reader
        self.__errstr = StreamGobbler(proc.getErrorStream())
        self.__errorreader = Reader(BufferedReader(InputStreamReader(self.__errstr)))
    
        self.__process = proc
        return proc
Example #3
0
    def _excmd(self, sshcmd):
        '''
        return (connected_ok, response_array)
        '''
        connected_ok = True
        resp = []
        try:
            conn = Connection(self.hostname)
            conn.connect()
            self.logger.info('ssh connection created.')
            isAuthenticated = conn.authenticateWithPassword(
                self.user, self.password)
            if not isAuthenticated:
                connected_ok = False
                self.logger.error('ssh failed to authenticatd.')
            else:
                self.logger.info('ssh authenticated.')
                sess = conn.openSession()

                self.logger.info('ssh session created.')
                sess.execCommand(sshcmd)
                self.logger.info('ssh command issued. cmd is %s' % sshcmd)

                stdout = StreamGobbler(sess.getStdout())
                br = BufferedReader(InputStreamReader(stdout))
                while True:
                    line = br.readLine()
                    if line is None:
                        break
                    else:
                        resp.append(line)
                self.logger.warning('ssh command output: ' % resp)
        except IOException, ex:
            connected_ok = False
            #print "oops..error,", ex
            self.logger.error('ssh exception: %s' % ex)
Example #4
0
def getSSHEnv(connection):
    """ Get the environment variables of an ssh remote server """
    print "Getting Environment Variables ..."
    '''
    sess = connection.openSession()
    sess.requestDumbPTY()
    sess.startShell()
    instr = StreamGobbler(sess.getStdout())
    stdin = BufferedReader(InputStreamReader(instr))
    # get the login shell information.
    #stdin.readLine()    # just delay it so as to be synchronized
    #stdin.readLine()    # just delay it so as to be synchronized
    while(1):
      c = stdin.read()
      if chr(c) == "]":
        c = stdin.read()
        if chr(c) == "$":
          break
    stdin.read()
    out = DataOutputStream(sess.getStdin())
    out.writeBytes("printenv\n")
    input = []
    flag = 0
    line = ""
    while 1:
      c = stdin.read()
      if chr(c) == "\n":
        input.append(line)
        line = ""
      else:
        line = line + chr(c);

      if chr(c) == "]":
        c = stdin.read()
        if chr(c) == "$":
          break
    environ = "".join(input)
    env = re.findall('(\S+)=(\S+)',environ)
    instr.close()
    out.close();
    out = None
    instr = None
    stdin = None
    sess.close()
    sess = None
    return env
    '''

    sess = connection.openSession()
    sess.requestDumbPTY()
    sess.startShell()
    instr = StreamGobbler(sess.getStdout())
    stdin = BufferedReader(InputStreamReader(instr))

    #wait
    while 1==1:
      c = stdin.read() # read the rest bytes before issueing cmd
      if chr(c) == "]":
        c = stdin.read()
        if chr(c) == "$":
          break

    out = DataOutputStream(sess.getStdin())
    #issue the command plus echo something(FINISH) to know when to unblock
    out.writeBytes("printenv && echo FINISH\n")
    input = []
    flag = 0
    while 1:
        line = stdin.readLine()
        if line is None:
            break
        line = line + "\n"
        input.append(line)
        if line.endswith("FINISH\n"):
            if flag == 1:
                break
            else:
                flag +=1
    environ = "".join(input)
    env = re.findall('(\S+)=(\S+)\n',environ)
    instr.close()
    instr = None
    stdin = None
    sess.close()
    sess = None
    return env
Example #5
0
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
Example #6
0
class ProcExecutor:
    """ Executor class for local OS command execution through Runtime and 
    conversation functions for getting the input and error streams and writing
    to output stream"""

    def __init__(self):
        self.__instr = None
        self.__errstr = None
        self.__inputreader = None
        self.__errortreader = None
        self.__outputwriter = None
        self.__process = None
        self.__env = []

    def exec(self,command):
        """ Execute an OS command. This function also starts three threads 
        that handle the input, error and output streams. Then the other 
        functions can be used to make a conversation with the os process."""
        rt = Runtime.getRuntime()
        proc = rt.exec(command)

        self.__outputwriter = DataOutputStream(proc.getOutputStream())
            
        # start a new thread for the input stream of the process and set the
        # Reader
        self.__instr = StreamGobbler(proc.getInputStream())
        self.__inputreader = Reader(BufferedReader(InputStreamReader(self.__instr)))

        # start a new thread for error stream of the process and set the 
        # Reader
        self.__errstr = StreamGobbler(proc.getErrorStream())
        self.__errorreader = Reader(BufferedReader(InputStreamReader(self.__errstr)))
    
        self.__process = proc
        return proc

    def input(self):
        """ Function for reading the output of a process.
        Wrapper for Reader readString function. """
        if self.__inputreader is None:
            print "Error inputstream 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 errorstream 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[:]:
            writer.write(i)
            writer.flush()
        writer.write('\n')
        writer.flush()

    def getEnv(self, var):
        return os._shellEnv.environment[var]

    def setEnv(self, var, value):
        os._shellEnv.environment[var] = value

    def close(self):
        self.__instr.close()
        self.__errstr.close()
        self.__instr = None
        self.__errstr = None
        self.__process.destroy()