python中使用ssh与str编码问题
python中使用ssh连接示例
if __name__ == '__main__':
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('127.0.0.1', 22, 'amlogic', 'Linux2022')
channel = ssh.get_transport().open_session()
channel.get_pty()
channel.invoke_shell()
channel.send('ls \n')
while True:
log = str(channel.recv(1024), 'utf-8','ignore').strip()
if 'FAILED :' in log:
break
channel.close()
ssh.close()
注意其中ls命令需要用换行符。
此外,str后的两个参数,表示decode的方式,与decode函数一致。
| 参数 | 含义 |
|---|---|
| bytes | 表示要进行转换的二进制数据。 |
| encoding="utf-8" | 指定解码时采用的字符编码,默认采用 utf-8 格式。当方法中只使用这一个参数时,可以省略“encoding=”,直接写编码方式即可。 |
| errors = "strict" | 指定错误处理方式,该参数的默认值为 strict。 |
errors可选择值可以是
strict:遇到非法字符就抛出异常。
ignore:忽略非法字符。
replace:用“?”替换非法字符。
xmlcharrefreplace:使用 xml 的字符引用。
使用strict时可能遇到报错
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe2 in position 1023: unexpected end of data

浙公网安备 33010602011771号