pythonpexpectreprpxssh

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


I am writing an application in Python, I am using pexpect ( more specifically the pxssh functionality) to execute a series of commands on a Cisco Router. I want to store the output returned to a variable intact with the whitespaces and the newlines.

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

After login and execute relevant command, I store the result in a dictionary:

data[command]=repr(s.before)

repr returns /n and the /r perfectly, however whitespaces are missing.

As an example the print(s.before) returns as below.

Snapshot of the print(s.before)

However with repr the best I am able to get (and consequently format) is as below:

snapshot when using repr

In where whitespaces and formatting are lost.

P.S. : I cannot write and read to the files. Any help appreciated.


Solution

  • As far as I understand, you're trying to save python string (with \n and whitespaces) and inject it in some html.

    If you're having trouble with html view, wrap your string into <pre> tag to preserve formatting (including spaces). This is not issue with python (again, as far as I understand), you can check this by printing your variable or counting whitespaces inside python