gpt4 book ai didi

python - 当您使用 Python 的 Paramiko 库进行 SSH 并从远程计算机的 CLI 获取输出时,是否有一种简单的方法可以消除垃圾值?

转载 作者:太空宇宙 更新时间:2023-11-03 13:14:51 26 4
gpt4 key购买 nike

我正在使用 Python 的 Paramiko 库通过 SSH 远程机器并从命令行获取一些输出。我看到很多垃圾打印以及实际输出。如何摆脱这个?

chan1.send("ls\n")
output = chan1.recv(1024).decode("utf-8")
print(output)
[u'Last login: Wed Oct 21 18:08:53 2015 from 172.16.200.77\r', u'\x1b[2J\x1b[1;1H[local]cli@BENU>enable', u'[local]cli@BENU#Configure',

我想从输出中消除 [2J\x1b[1;1Hu。它们是垃圾。

最佳答案

这不是垃圾。这些是 ANSI escape codes通常由终端客户端解释以漂亮地打印输出。

如果服务器配置正确,您只会在使用交互式终端时获得这些,换句话说,如果您请求 pseudo terminal session (如果您要使 session 自动化,则不应该这样做)。

Paramiko 会自动请求伪终端,如果你使用 SSHClient.invoke_shell ,因为它应该用于实现交互式终端。另见 How do I start a shell without terminal emulation in Python Paramiko?

如果您自动执行远程命令,最好使用 SSHClient.exec_command ,默认情况下不分配伪终端(除非您通过 get_pty=True 参数覆盖)。

stdin, stdout, stderr = client.exec_command('ls')

另见 What is the difference between exec_command and send with invoke_shell() on Paramiko?


或者作为解决方法,请参阅 How can I remove the ANSI escape sequences from a string in python .

虽然那是一种 hack,可能还不够。您可能会遇到交互式终端的其他问题,而不仅仅是转义序列。

您可能对“上次登录”消息和命令提示符 (cli@BENU>) 也不感兴趣。您不会通过 exec_command 获得这些。


如果由于服务器的某些特定要求或限制而需要使用“shell” channel ,请注意,在技术上可以在没有伪终端的情况下使用“shell” channel 。但是 Paramiko SSHClient.invoke_shell 不允许这样做。相反,您可以手动创建“shell ” channel 。参见 Can I call Channel.invoke_shell() without calling Channel.get_pty() beforehand, when NOT using Channel.exec_command() .


最后 u 不是实际字符串值的一部分(注意它在引号之外)。这表明字符串值采用 Unicode 编码。你想要那个!

关于python - 当您使用 Python 的 Paramiko 库进行 SSH 并从远程计算机的 CLI 获取输出时,是否有一种简单的方法可以消除垃圾值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33291631/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com