我想使用Python连接到远程服务器并执行进程,同时获取进程的返回代码和stderr(如果有)。之前有人做过类似的事情吗?我已经通过ssh实现了这一点,但我想从Python脚本中实现。祝好。
使用专门为此创建的ssh模块paramiko,而不是使用subprocess
。以下是一个示例:
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()
更新:该示例曾使用 ssh
模块,但现已弃用,paramiko 是提供 Python 中 SSH 功能的最新模块。
好的,你可以从Python中调用ssh...
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]