[paramiko] getting command output CORRECTLY from a channel

Marcin Krol mrkafk at gmail.com
Tue Nov 24 06:20:11 PST 2009


Hello,

There I was, happy user of SSHClient(). However, in order to use 
"set_combine_stderr" method on the Channel object (thanks, Todd!), I 
have to get a transport and then open channel and exec command in 
channel myself.

This means I have to channel.recv() standard output from the command 
myself, no? Bc I haven't found the way to pass a set_combine_stderr 
parameter to SSHClient() so it could set the channel accordingly.

So is the following way correct? I.e. is it likely to work with some 
strange scenarios like late response from ssh server etc?


     def execcmds(self):
         so = ''
         try:
             trn = self.conobj.get_transport()
             chn = trn.open_session()
             chn.set_combine_stderr(True)
             chn.exec_command(self.cmd)
         except SSHException, e:
             self.confailed = True
             return ('', '', str(e))

         # wait for it...
         i = 0
         while i < 10 and not chn.recv_ready():
             time.sleep(0.1)
             i += 1

         so = ''
         try:
             part = chn.recv(65536)
             while part:
                 so += part
                 part = chn.recv(65536)
         except SSHException, e:
             self.confailed = True
             return ('', '', str(e))
         except socket.timeout:
             self.confailed = True
             return ('', '', 'socket.timeout')

         return (so, '', '')


############
Don't pay attention to the triplet (stdout, stderr, exception_string) 
that the function returns, it's a leftover from version that have had 
std out and std err separate and returned both.





More information about the paramiko mailing list