Search code examples
pythonpython-2.7sshpopenplink

How to kill plink.exe when there's no output from stdout?


Plink.exe does not close when the process is finished. The code got stuck when trying to break the while loop by checking if output == ' ': break, but still no luck. I'm able to print the live output, but unable to break the loop when it's completed.

#Establish ssh connection to a server
def _establish_connection(self):
    connection='plink -ssh {}@{} -pw {}'.format(self.user,self.server,self.pw)
    self.sp = Popen(connection,stdin=PIPE,stdout=PIPE) 



#Trying to read live output from stdout and write to file
def _test_create_log(self,_system,_logdir):
     self._establish_connection()
     self.sp.stdin.write(_command)
     timestr = time.strftime("%Y%m%d-%H%M%S")
     dir_to_log = os.path.join(_logdir,_system + '_' + timestr + '.txt')
     with open(dir_to_log,'w+') as myLog:
         while True:
             output = self.sp.stdout.readline()
             output.decode('ASCII')
             if output != '': 
                 myLog.write(output)
                 print(output.strip())
             else: #Code does not reach here, plink not killed.
                 self.sp.kill()
                 break

Solution

  • Shell is a black box with an input and output. There's no way to detect that an output on one specific command has ended. All you can do is to add some magic string at the end of the output and look for that. Anyway, this is not the right solution.


    If you want Plink to close with the command, provide the command on Plink command-line, like:

    connection='plink -ssh {}@{} -pw {} {}'.format(self.user,self.server,self.pw,_command)
    

    Though way better is to use a native SSH library in Python, like Paramiko, instead of driving an external console application.

    See python paramiko run command.