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 中国大陆许可协议进行许可。

posted @   心比天高xzh  阅读(35)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起