Python os.forkpty why can't I make it work

大城市里の小女人 提交于 2019-12-21 06:19:33

问题


import pty
import os
import sys
import time

pid, fd = os.forkpty()

if pid == 0:
    # Slave
    os.execlp("su","su","MYUSERNAME","-c","id")

# Master
print os.read(fd, 1000)
os.write(fd,"MYPASSWORD\n")
time.sleep(1)
print os.read(fd, 1000)
os.waitpid(pid,0)
print "Why have I not seen any output from id?"

回答1:


You are sleeping for too long. Your best bet is to start reading as soon as you can one byte at a time.

#!/usr/bin/env python

import os
import sys

pid, fd = os.forkpty()

if pid == 0:
    # child
    os.execlp("ssh","ssh","hostname","uname")
else:
    # parent
    print os.read(fd, 1000)
    os.write(fd,"password\n")

    c = os.read(fd, 1)
    while c:
        c = os.read(fd, 1)
        sys.stdout.write(c)


来源:https://stackoverflow.com/questions/864826/python-os-forkpty-why-cant-i-make-it-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!