Skip to main content
 首页 » 编程设计

python之交互式 shell paramiko 如何像 exec_command 一样读取输入

2025年04月02日14lori

在没有交互式 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