The goal is to establish the reverse ssh connection from machine-a to machine-b, so I could ssh connect from machine-b to machine-a after the reverse connection is established.
After importing os module I go ahead and use os.system to ssh connect to a remote server using ssh -R 2210:localhost:22 [email protected] & command. Please note that the command line ends with & character because I want to place the ssh process in the background:
import os
result = os.system("ssh -R 2210:localhost:22 [email protected] &")
print("...started ssh connection", result)
But I am getting the error and as a result the ssh connection is not established:
Pseudo-terminal will not be allocated because stdin is not a terminal.
I have tried to run it with subprocess hoping it will work:
import subprocess
cmd = ["ssh", "-R", "2210:localhost:22", "[email protected]", "&"]
result = subprocess.Popen(cmd, shell=False)
but it throws another error:
bash: -c: line 0: syntax error near unexpected token `&'
Is there a way to run ssh connection from Python placing it at the background?
os.system. Never. Not under any circumstances. The limitations it adds tosubprocess.Popenare all for the worse: can't useshell=Falseto avoid injection attacks, can't pass arguments out-of-band from code to run, can't configure file descriptor initialization -- and those limitations actively prevent good security practices from being followed.&on asubprocess.Popencommand, because Python already starts your process in the background (which is to say, without an implicitwait). If you wanted a foreground process you'd have to use something likesubprocess.call()instead, or explicitly invoke a blocking function likecommunicate()orwait()on the returned object.&command is parsed and recognized by the shell before running the actual process. As you can see, this doesn't work when invoking a subprocess in Python (it likely calls something lower than the shell, such asexecv). Regardless, Popen technically already opens the process in the background. You can check on the process status withresultin your case.-Nargument), and ones that show how to do it with paramiko.