gpt4 book ai didi

python - Paramiko stdout.read给出 “AttributeError: '元组的对象没有属性 'read'”

转载 作者:行者123 更新时间:2023-12-02 14:05:59 24 4
gpt4 key购买 nike

我是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'

最佳答案

exec_command确实返回了stdin / stdout / stderr元组。
你要这个:

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

另一个不相关的事情是,您不能在每个命令之后关闭 SSHClient。因此,必须将其从 ExecSSHCommand函数的末尾移至脚本的末尾:
ssh.close()

关于python - Paramiko stdout.read给出 “AttributeError: '元组的对象没有属性 'read'”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64572888/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com