简体   繁体   中英

getting stuck at os.read() inside a fork

I have used the code below to create a child process, get inside an ssh container run a command inside the child and get its output.

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:
            #time.sleep(1)
            data = os.read(fd, 1024)
        except OSError:
            break
        if not data:
            break
        result.append(data)
    pid, status = os.waitpid(pid, 0)
    #pid, status = os.waitpid(pid,os.WNOHANG)
    return status, ''.join(result)

status, output = wall('localhost', "secret")
print status
print output

Even though this works the first time you call wall() (or sometimes the first few times you call wall()), if you call wall() again it gets stuck at data=os.read(fd,1024) or at os.waitpid(pid,0). Is there any solution to this working everytime I call wall().

Note: I'm not allowed to use external libraries like pexpect, paramiko etc.

Perhaps sometimes os.read doesn't wait for the password prompt. In that case only two options:

  • Use a specialized package for connecting by ssh; for example How to make ssh connection with python
  • Parse the output and pass the password only after prompt. Try to debug the first call of os.read; probably that will clarify unstable behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM