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

标签 python ssh paramiko

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

相关文章:

python - 每第 n 次迭代串联循环列表

python - 如何去掉 Pandas 群的中间部分,只保留头部和尾部?

git Permission denied (publickey),每次连接

python - Paramiko SSHException channel 关闭

python - 在 Django REST 中增加计数器字段的最佳位置

python - Pandas RegEx 提取子字符串上的第一个匹配项,传递的项目数错误

batch-file - 通过 plink 向 Cisco CLI 传递多个命令时出错

c++ - 如何将 .so 文件链接到 cpp 程序

python-2.7 - 如何使用paramiko在python脚本中给出sftp代理命令?

python - 直接从 SFTP 服务器将音频文件加载到 Python 语音识别模块(使用 Paramiko SFTPClient)