我有一个Juniper路由器,我正在尝试使用Python 3.7.1自动完成一些任务 . 我的代码完全运行一些命令,但有些命令会出错 . 以下是我的代码
import paramiko
def sshConnection(ip,command):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, port=22, username='username', password='password')
stdin, stdout, stderr = ssh.exec_command(command)
output = stdout.readlines()
return output
ip = '10.1.1.1'
command = 'show interfaces descriptions | match 1000 | no-more'
output = sshConnection(ip,command)
print('\n'.join(output))
以下是我面临的错误
Traceback (most recent call last):
File "C:\Users\Mu\Documents\Python Code\write_file - Stackoverflow.py", line 16, in <module>
output = sshConnection(ip,command)
File "C:\Users\Mu\Documents\Python Code\write_file - Stackoverflow.py", line 10, in sshConnection
output = stdout.readlines()
File "C:\Users\Mu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\paramiko\file.py", line 349, in readlines
line = self.readline()
File "C:\Users\Mu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\paramiko\file.py", line 334, in readline
return line if self._flags & self.FLAG_BINARY else u(line)
File "C:\Users\Mu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\paramiko\py3compat.py", line 156, in u
return s.decode(encoding)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 37: invalid start byte
其他路由器命令,如'show version'工作正常并显示正确的输出 . 输出似乎包含一些UTF-8编码不接受的字符 . 我无法找到解决此问题的方法 . 请帮我解决这个问题 . 谢谢 .
1 回答
问题出现是因为默认情况下Paramiko中
BufferedFile
类的readline
方法解码为UTF-8 . 并且似乎没有记录的方法来改变它 .但是,Paramiko在内部使用字节 . file.py中的readline方法以
return line if self._flags & self.FLAG_BINARY else u(line)
结束 . 所以,如果有办法设置这个FLAG_BINARY
,就没有翻译 . 同一类中的内部_set_mode
可以设置此标志 . 该标志在doc中被确认,但不是设置它的方式 .打开连接时,我无法找到设置标志的正确方法,但之后可能会设置标志 . 如果是这样,
readline
将返回字节 . 也许在任何阅读之前stdout._set_mode("rb")
才会奏效 . 请注意,starting underscore表示该函数是内部/未记录的,可能会更改,恕不另行通知 .另一种方法是使用
read
而不是readline
,但你必须处理行结尾 .