1

Assume there exists a python script resolve_ip.py which magically returns the string IP of a machine we care about.

I'm interested in learning how to achieve the python equivalent of the following bash command:

user@host:~$ ssh $(./resolve_ip.py)

In this bash example, after the python script runs, it is replaced or rather substituted with its return value which is, in turn, provided as a input to the program ssh. The result is, the python program terminates and the user interacts with ssh initialization.

The problem is, this solution requires the use of either 2 scripts (a bash script to run ssh, combined with the python script to return the arguments) or alternatively human intervention to type the bash command directly as formatted above.

Question:

Is there a way, only using python, to start/fork an interactive service (like ssh), by using subprocess or some comparable module, and have this forked child process remain alive in the foreground, even after its parent (python) has sys.exit()'d?

Considerations:

In this case, the point of this question is not to script the submission of ssh credentials to ssh from within Python. It is how to spawn a subprocess which continues to run foregrounded after its parent/spawner terminates.

EDIT: The following resources are related:

Community
  • 1
  • 1
mekarpeles
  • 365
  • 3
  • 9

1 Answers1

5

I think you want to "exec". Like this:

import resolve_ip
import os
host = resolve_ip.get_host_to_use() # you figure this part out
os.execlp('ssh', 'ssh', host)

That will replace the Python interpreter process image with the ssh process image, and keep running. So you will end up as if you had run ssh instead of Python, and the interpreter will no longer execute at all.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • 1
    `execlp` is from `os`, not `subprocess`, also, it's called like `execlp('ssh', 'ssh', host)` (second `'ssh'` is `argv[0]` in the child process). – bereal Mar 16 '14 at 07:17
  • Thanks john-zwinck & @bereal. os.execlp accomplishes the task. I've heard that subprocess is preferable to os.system. Is there a subprocess alternative to os.execlp which offers greater safety (with respect to arbitrary bash commands being run)? – mekarpeles Mar 16 '14 at 08:01
  • 1
    No, subprocess is for spawning processes, which is not what you want. – John Zwinck Mar 16 '14 at 08:02
  • 1
    @mekarpeles as far as I know, `exec*` functions are perfectly safe from this point of view, they just wrap the corresponding system calls. – bereal Mar 16 '14 at 08:12
  • 1
    @mekarpeles: `subprocess` calls `os.execvp()` in a `fork()`-ed child process. It is not what you want. – jfs Mar 16 '14 at 10:48