how to give subprocess a password and get stdout at the same time

后端 未结 1 1777
清歌不尽
清歌不尽 2021-01-15 23:15

I\'m trying to check for the existence of an executable on a remote machine, then run said executable. To do so I\'m using subprocess to run ssh ls

1条回答
  •  伪装坚强ぢ
    2021-01-15 23:39

    How about using authorized_keys. Then, you don't need to input password.

    You can also go hard way (only work in Linux):

    import os
    import pty
    
    def wall(host, pw):
        pid, fd = pty.fork()
        if pid == 0: # Child
            os.execvp('ssh', ['ssh', host, 'ls', '/usr/bin/wall'])
            os._exit(1) # fail to execv
    
        # read '..... password:', write password
        os.read(fd, 1024)
        os.write(fd, pw + '\n')
    
        result = []
        while True:
            try:
                data = os.read(fd, 1024)
            except OSError:
                break
            if not data:
                break
            result.append(data)
        pid, status = os.waitpid(pid, 0)
        return status, ''.join(result)
    
    status, output = wall('localhost', "secret")
    print status
    print output
    

    http://docs.python.org/2/library/pty.html

    0 讨论(0)
提交回复
热议问题