Interative shell paramiko如何读取exec_command之类的输入

时间:2016-05-02 17:43:00

标签: python paramiko

在没有交互式shell的情况下使用paramiko exec_command时,很容易获得输出。

但是我需要使用交互式shell,读取单个命令的输出似乎很痛苦。我找不到演示或任何这方面的例子。

我尝试使用类似:Implement an interactive shell over ssh in Python using Paramiko?

的内容

但它的形状非常糟糕。

2 个答案:

答案 0 :(得分:1)

您不必使用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

答案 1 :(得分:0)

使用链接中给出的解决方案后,“你的形状真的很糟糕”是什么意思?

输出中包含一些不必要的字符,因此我将其删除,请参阅已编辑的解决方案。