Paramiko stdout.read给出“AttributeError:‘tuple’对象没有属性‘read’”

2024-10-04 09:25:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,所以如果我错过了什么,请道歉

我正在创建一个脚本,它可以连接到Linux机器来运行几个命令,并输出这些结果以在HTML报告中使用。当我运行脚本(减去HTML报告生成)时,当命令传递给执行CLI命令的函数时,它会抛出以下错误:

AttributeError: 'tuple' object has no attribute 'read'

当将有大约30个不同的CLI命令传递给函数并需要返回结果时,如何处理函数中的此类错误

import paramiko as paramiko
from paramiko import SSHClient

# Connect

ssh = SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('', username='', password='', look_for_keys=False)

def ExecSSHCommand(cli):
    stdout = ssh.exec_command(cli)

    print(type(stdout))  # <class 'paramiko.channel.ChannelFile'>

    # Print output of command. Will wait for command to finish.
    print(f'STDOUT: {stdout.read().decode("utf8")}')

    stdout.close()

    # Close the client itself
    ssh.close()

status = ExecSSHCommand('show status') 
service = ExecSSHCommand('show services')

这是全部错误:

line 55, in <module>
  status = ExecSSHCommand('show status') line 22,
in ExecSSHCommand print(f'STDOUT: {stdout.read().decode("utf8")}')
AttributeError: 'tuple' object has no attribute 'read' 

Tags: 命令脚本paramikoreadclihtml报告status
1条回答
网友
1楼 · 发布于 2024-10-04 09:25:26

exec_command确实返回一个stdin/stdout/stderr元组

你想要这个:

stdin, stdout, stderr = ssh.exec_command(cli)

另一件不相关的事情是,您不能在each命令之后关闭SSHClient。因此必须将它从ExecSSHCommand函数的末尾移到脚本的末尾:

ssh.close()

相关问题 更多 >