在没有交互式 shell 的情况下使用 paramiko exec_command 时,很容易获得输出。
但是我需要使用交互式 shell,读取单个命令的输出似乎很痛苦。我找不到演示或任何示例。
我尝试使用类似的东西:Implement an interactive shell over ssh in Python using Paramiko?
但它的状态真的很糟糕。
最佳答案
你不必为此使用 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
关于python - 交互式 shell paramiko 如何像 exec_command 一样读取输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36988385/