Paramiko stdout.read gives "AttributeError: 'tuple' object has no attribute 'read'"
Paramiko stdout.read gives "AttributeError: 'tuple' object has no attribute 'read'"
我是 Python 的新手,如有遗漏,请见谅。
我正在创建一个脚本,它可以连接到 Linux 台机器以执行 运行 几个命令并输出这些结果以用于 HTML 报告。当我 运行 脚本(减去 HTML 报告生成)时,当命令传递给执行 CLI 命令的函数时,它抛出以下错误:
AttributeError: 'tuple' object has no attribute 'read'
当大约有 30 个不同的 CLI 命令传递给函数并且需要 return 结果时,我该如何处理函数中的此类错误?
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
确实是returns一个stdin/stdout/stderr元组。
你想要这个:
stdin, stdout, stderr = ssh.exec_command(cli)
另一个不相关的事情是你不能在每个命令之后关闭SSHClient
。所以这必须从 ExecSSHCommand
函数的末尾移动到脚本的末尾:
ssh.close()
我是 Python 的新手,如有遗漏,请见谅。
我正在创建一个脚本,它可以连接到 Linux 台机器以执行 运行 几个命令并输出这些结果以用于 HTML 报告。当我 运行 脚本(减去 HTML 报告生成)时,当命令传递给执行 CLI 命令的函数时,它抛出以下错误:
AttributeError: 'tuple' object has no attribute 'read'
当大约有 30 个不同的 CLI 命令传递给函数并且需要 return 结果时,我该如何处理函数中的此类错误?
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
确实是returns一个stdin/stdout/stderr元组。
你想要这个:
stdin, stdout, stderr = ssh.exec_command(cli)
另一个不相关的事情是你不能在每个命令之后关闭SSHClient
。所以这必须从 ExecSSHCommand
函数的末尾移动到脚本的末尾:
ssh.close()