0

How can I change a python script's STDIN to be the STDOUT of another process in the middle of the runtime of that script?

I'm writing a python application that runs as a non-root user and that launches a child process as root using subprocess. Due to complexities in how MacOS handles privilege escalation, the child process's parent process is no longer the python script that created it, the child looses its tty, and the stdin/stdout communication gets broken between parent & child.

Since the child process is root, I can find the actual parent processes' PID and TTY using ps

result = os.popen( 'ps -eo "pid, tty, command" | grep -iE "[s]pawn_root.py"' ).read().splitlines().pop().split()

pid = result[0]
tty = result[1]

And I was successfully able to attach the stdin of the child process to the tty of the parent process as follows

sys.stdin = open( '/dev/' +str(tty), 'r' )

Unfortunately, it seems that attaching to the tty of the parent process is not the same as attaching to the STDOUT of the parent process. I guess it's a path to a different file descriptor, somehow.

If I have a python process A running as root on MacOS, how can I attach that processes' STDIN to the STDOUT of process B, given the PID or Command name of process B?

Michael Altfield
  • 2,083
  • 23
  • 39
  • Please reconsider `ps | grep` -- it's error-prone at the best of times, and for Python there are 3rd-party libraries that do a better job; see https://pypi.org/project/psutil/ – Charles Duffy Oct 08 '22 at 22:23
  • That said -- _in general_, you need to redirect programs' IO _before_ those programs are started. There are exceptions, but they're platform-specific and painful, and the workarounds I personally recall seeing (in addition to being utter hacks) were Linux-only. – Charles Duffy Oct 08 '22 at 22:23
  • Definitely. This is not production code. I'm first just trying to make it work :) – Michael Altfield Oct 08 '22 at 22:24
  • GUI privilege escalation through the OS is already platform-specific, so this solution is limited to MacOS – Michael Altfield Oct 08 '22 at 22:25
  • What's the context? I wonder if there might be an alternative -- something like having your program's stdout be tee'd to a script that can be signaled to switch from bitbucketing the output to redirecting it to a FIFO, or running it inside a tmux-style tool, or similar. – Charles Duffy Oct 08 '22 at 22:25
  • 1
    Context is this question https://stackoverflow.com/questions/73999365/communicating-with-root-child-process-launched-with-osascript-with-administrato – Michael Altfield Oct 08 '22 at 22:25
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/248663/discussion-between-charles-duffy-and-michael-altfield). – Charles Duffy Oct 08 '22 at 22:28

0 Answers0