簡體   English   中英

Python:UnicodeDecodeError:'utf-8'編解碼器無法解碼位置37的字節0x96:無效的起始字節

[英]Python: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 37: invalid start byte

我有一個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編碼不接受的字符。 我找不到該問題的解決方案。 請幫我解決這個問題。 謝謝。

出現問題是因為默認情況下, readlineBufferedFile類的readline方法解碼為UTF-8。 而且似乎沒有記錄的方式可以改變這一點。

但是,Paramiko在內部使用字節。 在ReadLine方法file.py與終止return line if self._flags & self.FLAG_BINARY else u(line) 因此,如果有一種方法可以設置此FLAG_BINARY ,則不會進行翻譯。 同一類中的內部_set_mode可以設置此標志。 該標志在doc中被確認,但不是設置它的方式。

打開連接時,我找不到正確的方法來設置標志,但是之后可能會設置標志。 如果是這樣, readline將返回字節。 也許在任何讀取之前都可以使用stdout._set_mode("rb") 請注意, 下划線開頭表示該功能是內部的/未記錄的,可能會更改,恕不另行通知。

另一種方法是使用read而不是readline ,但是您將不得不處理行尾。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM