【发布时间】:2016-08-27 13:39:31
【问题描述】:
在没有交互式 shell 的情况下使用 paramiko exec_command 时,很容易得到输出。
但是,我需要使用交互式 shell,而且读取单个命令的输出似乎很痛苦。我找不到演示或任何示例。
我尝试使用类似的东西:Implement an interactive shell over ssh in Python using Paramiko?
但它的状态非常糟糕。
【问题讨论】:
在没有交互式 shell 的情况下使用 paramiko exec_command 时,很容易得到输出。
但是,我需要使用交互式 shell,而且读取单个命令的输出似乎很痛苦。我找不到演示或任何示例。
我尝试使用类似的东西:Implement an interactive shell over ssh in Python using Paramiko?
但它的状态非常糟糕。
【问题讨论】:
使用链接中给出的解决方案后,“情况非常糟糕”是什么意思?
输出中有一些不必要的字符,所以我删除了它们,请参阅edited解决方案。
【讨论】:
您不必为此使用paramiko。
只需使用paramiko 打开无密码ssh 连接,然后使用subporcess 模块实现您的方法。
例如:
def run_shell_remote_command(remote_host, remote_cmd):
p = subprocess.Popen(['ssh', '-nx', remote_host, remote_cmd], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
if p.returncode != 0:
raise RuntimeError("%r failed, status code %s stdout %r stderr %r" % (
remote_cmd, p.returncode, stdout, stderr))
return stdout.strip() # This is the stdout from the shell command
【讨论】:
RPyc。如果您有兴趣,我会在此处发布使用示例。