コード例 #1
0
ファイル: ssh.py プロジェクト: gidiko/gridapp
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
コード例 #2
0
ファイル: ssh.py プロジェクト: gidiko/gridapp
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
コード例 #3
0
ファイル: sysprocess.py プロジェクト: gidiko/gridapp
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()