How to execute a process remotely using python

2020-01-27 02:49发布

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.

标签: python ssh
3条回答
甜甜的少女心
2楼-- · 2020-01-27 03:23

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.

查看更多
Juvenile、少年°
3楼-- · 2020-01-27 03:34

Maybe if you want to wrap the nuts and bolts of the ssh calls you could use Fabric This library is geared towards deployment and server management, but it could also be useful for these kind of problems.

Also have a look at Celery. This implements a task queue for Python/Django on various brokers. Maybe an overkill for your problem, but if you are going to call more functions on multiple machines it will save you a lot of headache managing your connections.

查看更多
做个烂人
4楼-- · 2020-01-27 03:36

Well, you can call ssh from python...

import subprocess
ret = subprocess.call(["ssh", "user@host", "program"]);

# or, with stderr:
prog = subprocess.Popen(["ssh", "user@host", "program"], stderr=subprocess.PIPE)
errdata = prog.communicate()[1]
查看更多
登录 后发表回答