我用下面的代码创建了一个子进程,进入一个ssh容器,在子进程中运行一个命令,并得到它的输出。
import os
import pty
def wall(host, pw):
pid, fd = pty.fork()
if pid == 0: # Child
os.execvp('ssh', ['ssh', host, 'ls', '/usr/bin/wall'])
os._exit(1) # fail to execv
# read '..... password:', write password
os.read(fd, 1024)
os.write(fd, pw + '\n')
result = []
while True:
try:
#time.sleep(1)
data = os.read(fd, 1024)
except OSError:
break
if not data:
break
result.append(data)
pid, status = os.waitpid(pid, 0)
#pid, status = os.waitpid(pid,os.WNOHANG)
return status, ''.join(result)
status, output = wall('localhost', "secret")
print status
print output
尽管第一次调用wall()(或者前几次调用wall())就能正常工作,但如果你再次调用wall(),就会卡在data=os.read(fd,1024)或者os.waitpid(pid,0)。
注意:我不允许使用外部库,如peexpect,paramiko等。
也许有时os.read不会等待密码提示,在这种情况下只有两个选择。