pythonlinuxterminalsubprocessautossh

autossh not working when executed in python


I am trying to create ssh reverse tunnel. When I run the below command on terminal it works greate:

autossh -M 10876 -N -f -o PubkeyAuthentication=yes -o PasswordAuthentication=no -i /root/.ssh/id_rsa -R 6666:localhost:22 root@**.**.**.** -p 2233

But when I run it in python with os.system() or using subprocess it's not working. When I check the processes list the process is created and running and has no difference with the last method.(running directly in terminal)

python code:

command ='autossh -M 10876 -N -f -o PubkeyAuthentication=yes -o PasswordAuthentication=no -i /root/.ssh/id_rsa -R 6666:localhost:22 root@**.**.**.** -p 2233'
proc = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE, shell=True)

Any idea What's the problem?


Solution

  • when you are using shell=True, you don't want to use shlex.split() on the command arguments... it should just be a string.

    Since you are passing args to Popen as a sequence, the first arg (autossh) is used as the command, and the rest of the args are actually passed to the shell, not to autossh.

    So... you can either remove shell=True, or pass args as a string by removing use of shlex.split().

    https://docs.python.org/2/library/subprocess.html#subprocess.Popen