Dev Ops Ranga
Dev Ops Ranga

Reputation: 213

Python subprocess to execute remote server commands

I have to execute python script that reside in remote machine and I am using below script:

from subprocess import call
ip = 1.1.1.1
call(["ssh", ip, "\"cd scripts; python -u get_details.py --web_server\""])

getting below error:

bash: cd scripts; python -u get_details.py --web_server: command not found

running in bash command line directly :

 ssh 1.1.1.1 "cd scripts; python -u get_details.py --web_server"

Asking below input and returning output

 1. USA
 2. UK
 Choose input: 1

 www.cisco_us.com is up 

Please let me how fix or any other better way to achive this in python

Upvotes: 1

Views: 3198

Answers (2)

Léopold Houdin
Léopold Houdin

Reputation: 1525

A way to make sure that your arguments are always prepared correctly is to use python's shlex module. You can do the following:

import shlex
import subprocess

ip = '1.1.1.1'
cmd = "ssh {} 'cd scripts; python -u get_details.py --web_server'".format(ip)

subprocess.call(shlex.split(cmd))

It ensures your arguments are correctly prepared.


I'd also recommend you to have a look at Paramiko. It's a python's library that helps you managing SSH connections.

Upvotes: 0

Florian Weimer
Florian Weimer

Reputation: 33719

You need to drop the quotation marks because the shell removes them. This:

ssh 1.1.1.1 "cd scripts; python -u get_details.py --web_server"

is equivalent to:

call(["ssh", ip, "cd scripts; python -u get_details.py --web_server"])

If you use call this way, there is no shell involved on the client side (which is a good thing), only on the server side.

Upvotes: 2

Related Questions