python paramiko invoke_shell recv得到了奇怪的字符

python paramiko invoke_shell recv得到了奇怪的字符,python,paramiko,Python,Paramiko,我正在使用paramiko从交换机获取信息。手动步骤是: 通过ssh登录到交换机 运行一个简单的命令 以下是输出: SW10 [standalone: master] > show interfaces ethernet 1/32 status Port Operational state Speed Negotiation ---- --------------

我正在使用paramiko从交换机获取信息。手动步骤是:

  • 通过ssh登录到交换机
  • 运行一个简单的命令
  • 以下是输出:

    SW10 [standalone: master] > show interfaces ethernet 1/32 status
    
    Port                   Operational state           Speed                  Negotiation
    ----                   -----------------           -----                  -----------
    Eth1/32                Up                          10 Gbps                No-Negotiation
    
    
    您可以只看到文本输出

    但是当我通过脚本运行这个时,我得到了以下奇怪的字符

    导入paramiko
    导入时间
    ssh=paramiko.SSHClient()
    ssh.set_缺少_主机_密钥_策略(paramiko.AutoAddPolicy())
    ssh.connect('10.10.21.22',用户名='admin',密码='pass')
    channel=ssh.invoke_shell()
    resp=信道recv(9999)
    show\u interface\u cmd=“show interfaces ethernet 1/21状态\r\n”
    channel.send(显示界面命令)
    resp=信道recv(9999)
    打印(resp)
    
    输出:

    b'\rSW10 [standalone: master] > show interfaces ethernet 1/26 status\r\r\n\x1b[?1h\x1b=\r\r\nPort
                Operational state           Speed                  Negoti \x08ation              \r\n----
     -----------------           -----                  ------ \x08-----              \r\nEth1/26                Up
                      10 Gbps                No-Neg \x08otiation           \r\n\r\x1b[K\x1b[?1l\x1b>\rSW10 [standalone: master] > \r\r\n\rSW10 [standalone: master] > '
    
    然后,如果我发送另一个正确的命令并尝试使用
    recv
    获取响应,则输出将包含错误

    我的问题是为什么我得到这种奇怪的输出?
    如何以正确的方式处理这个问题?谢谢。

    channel=ssh.exec\u command()
    替换
    channel=ssh.invoke\u shell()

    另外:“resp”输出中的“b”表示文本应该变成byte中的bytes文本。如果对字符串进行解码,则会得到一个字符串(此处跳过Martin Prikry评论中建议的可设置选项)。根据解码类型,可能会出现错误,也可能不会。例如,我在下面的示例代码中使用了“utf-8”字符集进行解码。这可以被任何其他类型的字符集解码所代替。另见。关于这方面的python 3文档可以在

    例如:

    b'\xE2\x82\xAC'.解码('UTF-8')

    结果:“€”

    或:

    b'\xc2\xb5'.解码('utf-8')

    结果:“µ”

    resp = b'\rSW10 [standalone: master] > show interfaces ethernet 1/26 status\r\r\n\x1b[?1h\x1b=\r\r\nPort
                Operational state           Speed                  Negoti \x08ation              \r\n----
     -----------------           -----                  ------ \x08-----              \r\nEth1/26                Up
                      10 Gbps                No-Neg \x08otiation           \r\n\r\x1b[K\x1b[?1l\x1b>\rE2E-M9958-102Y-SW10 [standalone: master] > \r\r\n\rSW10 [standalone: master] > '
    
    decoded_resp = resp.decode("utf-8")  # "utf-8" is replaceable by any other type of character-set.
    
    print(decoded_resp )