pseudo tty破除无法自动输入密码的限制

Posted on 2018-01-02 19:15  #大囚长#  阅读(154)  评论(0编辑  收藏  举报

没有root权限,没有ssh密钥对,又想自动输入密码咋办?

#!/usr/bin/python
# simplest builtin python pseudo-tty for ssh password. meuh 
# http://unix.stackexchange.com/a/276385/119298
import os
def run(cmd,*args):
    pid, fd = os.forkpty()
    if pid==0: # child
        os.execlp(cmd,*args)
    while True:
        data = os.read(fd,1024)
        print data
        if "password:" in data:    # ssh prompt
            os.write(fd,"password\n")
        elif data.endswith("$ ") or data.endswith("# "):  # bash prompt for input
            cmd = raw_input() + "\n"
            os.write(fd, cmd)

run("ssh", "ssh", "-p", "端口号", "root@10.1.1.1")