import pty, os, select, time
def try_su(user, pw, timeout=10):
    pid, fd = pty.fork()
    if pid == 0:
        os.execvp("su", ["su", user, "-c", "echo SUCESS_$(id -u)"])
    buf=b""; sent=False; start=time.time(); status=None
    while time.time()-start < timeout:
        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,(pw+"\n").encode()); sent=True
        wpid,wstatus=os.waitpid(pid,os.WNOHANG)
        if wpid:
            status=wstatus; break
    if status is None:
        try: os.kill(pid,9); status=os.waitpid(pid,0)[1]
        except Exception: pass
    return repr(buf), status
out,st = try_su("ubuntu","wrongpass123")
print("STATUS:", st)
print("OUT:", out)
