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

Is there a simple way to get rid of junk values that come when you SSH using Python's Paramiko library and fetch output from CLI of a remote machine?

我正在使用 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。他们是垃圾。

这其实不是垃圾。字符串前的 u 表示这是一个 unicode 字符串。 \x1b[2J\x1b[1;1H 是转义序列。我不知道它到底应该做什么,但是当我打印出来时它似乎清除了屏幕。

要了解我的意思,请尝试以下代码: for string in output: print string

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

如果服务器配置正确,你只会得到这些,当你使用交互式终端时,换句话说,如果你为会话请求 pseudo terminal(你不应该,如果你正在自动化会话)。

Paramiko 自动请求伪终端,如果你使用 SSHClient.invoke_shell, as that is supposed to be used for implementing an interactive terminal. See also

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

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

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

虽然这只是一个 hack,可能还不够。交互式终端可能还有其他问题,不仅仅是转义序列。

您可能对 "Last login" 消息和命令提示符 (cli@BENU>) 特别不感兴趣。你不会用 exec_command.

得到这些

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


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