#!/usr/bin/env python3
"""Tiny SSH-with-password runner — uses stdlib pty, no sshpass needed.
Usage: sshrun.py <host> <user> <password> <command...>
"""
import os, pty, sys, time, select

def run(host, user, password, cmd, timeout=60):
    pid, fd = pty.fork()
    if pid == 0:
        os.execvp("ssh", ["ssh",
            "-o","StrictHostKeyChecking=no",
            "-o","UserKnownHostsFile=/dev/null",
            "-o","PreferredAuthentications=password",
            "-o","PubkeyAuthentication=no",
            "-o","NumberOfPasswordPrompts=1",
            "-o","LogLevel=ERROR",
            f"{user}@{host}", cmd])
    buf = b""
    end = time.time() + timeout
    sent_pw = False
    while time.time() < end:
        r,_,_ = select.select([fd], [], [], 1.0)
        if not r: continue
        try: chunk = os.read(fd, 4096)
        except OSError: break
        if not chunk: break
        buf += chunk
        if not sent_pw and b"assword:" in buf:
            os.write(fd, password.encode()+b"\n")
            sent_pw = True
    try: os.waitpid(pid, 0)
    except: pass
    s = buf.decode(errors="replace")
    # strip the whole password-prompt line (including "user@host's " prefix)
    for marker in ("password:", "Password:"):
        i = s.find(marker)
        if i >= 0:
            line_start = s.rfind("\n", 0, i) + 1  # 0 if no preceding newline
            line_end = s.find("\n", i)
            if line_end >= 0:
                s = s[:line_start] + s[line_end+1:]
    return s

if __name__ == "__main__":
    print(run(sys.argv[1], sys.argv[2], sys.argv[3], " ".join(sys.argv[4:])))
