import pty, os, select, time
pid, fd = pty.fork()
if pid == 0:
    os.execvp("su", ["su", "-", "ubuntu", "-c", "id; whoami"])
buf=b""; sent=False; start=time.time()
while time.time()-start < 12:
    r,_,_ = select.select([fd],[],[],0.4)
    if r:
        try: data=os.read(fd,1024)
        except OSError: break
        if not data: break
        buf+=data
        if not sent and b"assword" in buf:
            os.write(fd,b"WRONGPW123\n"); sent=True
    wpid,wstatus=os.waitpid(pid,os.WNOHANG)
    if wpid:
        break
try:
    # drain
    for _ in range(10):
        r,_,_=select.select([fd],[],[],0.4)
        if r:
            try: d=os.read(fd,1024)
            except OSError: break
            if not d: break
            buf+=d
except Exception: pass
print(repr(buf))
