gpt4 book ai didi

python - 当标准输出没有输出时如何杀死 plink.exe?

转载 作者:太空宇宙 更新时间:2023-11-03 14:14:07 27 4
gpt4 key购买 nike

进程完成后,Plink.exe 不会关闭。当试图通过检查 if output == ' ':break 来打破 while 循环时,代码被卡住了,但仍然没有运气。我可以打印实时输出,但无法在完成后中断循环。

#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

最佳答案

Shell 是一个带有输入和输出的黑盒子。无法检测某个特定命令的输出是否已结束。您所能做的就是在输出末尾添加一些魔术字符串并查找它。无论如何,这不是正确的解决方案。

<小时/>

如果您希望使用该命令关闭 Plink,请在 Plink 命令行上提供该命令,例如:

connection='plink -ssh {}@{} -pw {} {}'.format(self.user,self.server,self.pw,_command)
<小时/>

更好的方法是使用 Python 中的 native SSH 库,例如 Paramiko ,而不是驱动外部控制台应用程序。

参见python paramiko run command .

关于python - 当标准输出没有输出时如何杀死 plink.exe?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48313514/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com