Skip to main content
 首页 » 编程设计

python之模拟 paramiko.SSHClient().exec_command()

2024年10月24日18pengyingh

我需要通过 ssh.exec_command() 模拟执行一些远程命令 它返回元组 (stdin, stdout, stderr) 作为 paramiko.ChanelFile 对象。

因此,我将命令输出为字符串(我希望 exec_command() 返回)以及如何使用我的输出字符串创建 ChanelFile 对象的问题。

伪代码:

    def send_command(self, cmd) 
        self.client.connect(hostname=self.host, 
                            username=self.user, 
                            password=self.password, 
                            timeout=self.timeout) 
        stdin, stdout, stderr = self.client.exec_command(cmd) 
 
        return stdin, stdout, stderr 
 
    if __name__ == '__main__': 
        stdin, stdout, stderr = report.send_command('ls -la') 
        resp = stdout.read().strip() 

所以我需要创建 stout 才能在其上运行 read() 方法。

请您参考如下方法:

参见 https://stackoverflow.com/a/8168742/5512755 MagicMock 也适用于此。

stdout = mock.MagicMock() 
stdout.read().strip.return_value = "file1\nfile2\nfile3\n" 

会成功的。