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
本文作者:心比天高xzh
本文链接:https://www.cnblogs.com/xzh-personal-issue/p/17115549.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步