Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a process remotely using python

Tags:

python

ssh

I want to connect to and execute a process on a remote server using Python. I want to be able to get the return code and stderr (if any) of the process. Has anyone ever done anything like this before. I have done it with ssh, but I want to do it from Python script.

Cheers.

like image 582
stinkypyper Avatar asked Jun 03 '09 20:06

stinkypyper


People also ask

How do I run a python script remotely?

Using the paramiko library – a pure python implementation of SSH2 – your python script can connect to a remote host via SSH, copy itself (!) to that host and then execute that copy on the remote host. Stdin, stdout and stderr of the remote process will be available on your local running script.


1 Answers

Use the ssh module called paramiko which was created for this purpose instead of using subprocess. Here's an example below:

from paramiko import SSHClient client = SSHClient() client.load_system_host_keys() client.connect("hostname", username="user") stdin, stdout, stderr = client.exec_command('program') print "stderr: ", stderr.readlines() print "pwd: ", stdout.readlines() 

UPDATE: The example used to use the ssh module, but that is now deprecated and paramiko is the up-to-date module that provides ssh functionality in python.

like image 143
aculich Avatar answered Oct 21 '22 00:10

aculich