1

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

3 Comments

which is best method and reliable ? Paramiko or configure ssh passwordless and use subprocess
I would recommend Paramiko. You have more control, and it's probably more secure.
Ok Let me try it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.