gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:29:05 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;1H ] 和 u 。它们是垃圾。

最佳答案

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

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

如果您使用 SSHClient.invoke_shell,Paramiko 会自动请求伪终端。 ,因为它应该用于实现交互式终端。另请参阅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 .

尽管这只是一种黑客行为,而且可能还不够。您可能会遇到交互式终端的其他问题,而不仅仅是转义序列的问题。

您可能对“上次登录”消息和命令提示符 (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/57633222/

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