import subprocess
import os
r=open("sad.txt",'a')
p = subprocess.Popen("ssh.exe root@192.168.58.154", stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = False)
p.stdin.write('password\n')
p.stdin.write('ifconfig\n')
while p.stdout.readline()!=' ':
line = p.stdout.readline() #如果p.stdout中内容被读完之后,程序会卡在这里
#line = line.strip()
print line
r.write(line)
这个卡死如何解决,这时候结束当前进程也没办法结束
或者如何判断卡死,然后p.kill()或“ctrl+c”当前进程
ssh执行p.stdin.write('exit\n')也不行,因为ssh exit之后还会跳回登录界面,进程还是没有结束
First of all, I point out that there is a problem with this paragraph. This is a printing problem. p.stdout.readline() != '' should not be placed in a while, because after the data is read, it will be discarded, so The complete data cannot be printed or written to the sad.txt file. Secondly, I think p.stdout should be made non-blocking to solve the stuck problem
This stuck is probably caused by the ssh process not exiting.
The reason why it gets stuck is because the pipe is empty after reading the last line, and for the
ifconfig
command, the last line is not a space but n:To prevent death caused by IO, the officially recommended method is to use
communicate
, such as this: