保留通过 ssh 执行命令收到的响应的格式(空格和换行符)

Preserve the formatting(whitespace & newlines) of the response received from executing a command over ssh

我正在 Python 中编写应用程序,我正在使用 pexpect(更具体地说是 pxssh 功能)在 Cisco 路由器上执行一系列命令。我想使用 whitespacesnewlines 将返回的输出原封不动地存储到一个变量中。

s = pxssh.pxssh(options={
        "StrictHostKeyChecking": "no",
        "UserKnownHostsFile": "/dev/null"})

登录并执行相关命令后,我将结果存储在字典中:

data[command]=repr(s.before)

repr returns /n/r 完美,但是缺少 whitespaces

例如 print(s.before) returns 如下。

但是 repr 我能得到的最好的(以及格式)如下:

其中 whitespaces 和格式丢失。

P.S。 : 我无法写入和读取文件。任何帮助表示赞赏。

据我了解,您正在尝试保存 python 字符串(带有 \n 和空格)并将其注入某些 html.

如果您在使用 html 视图时遇到问题,请将您的字符串包装到 <pre> 标记中以保留格式(包括空格)。这不是 python 的问题(同样,据我所知),您可以通过打印变量或计算 python

中的空格来检查这一点