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?

≯℡__Kan透↙ 提交于 2019-12-08 13:56:31

It's not a junk. These are ANSI escape codes that are normally interpreted by a terminal client to pretty print the output.

If the server is correctly configured, you get these only, when you use an interactive terminal, in other words, if you requested a pseudo terminal for the session (what you should not, if you are automating the session).

The Paramiko automatically requests the pseudo terminal, if you used the SSHClient.invoke_shell, as that is supposed to be used for implementing an interactive terminal. See also How do I start a shell without terminal emulation in Python Paramiko?

If you automate an execution of remote commands, you better use the SSHClient.exec_command, which does not allocate the pseudo terminal by default (unless you override by the get_pty=True argument).

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

Or as a workaround, see How can I remove the ANSI escape sequences from a string in python.

Though that's rather a hack and might not be sufficient. You might have other problems with the interactive terminal, not only the escape sequences.

You particularly are probably not interested in the "Last login" message and command-prompt (cli@BENU>) either. You do not get these with the exec_command.


And finally the u is not a part of the actual string value (note that it's outside the quotes). It's an indication that the string value is in the Unicode encoding. You want that!

This is actually not junk. The u before the string indicates that this is a unicode string. The \x1b[2J\x1b[1;1H is an escape sequence. I don't know exactly what it is supposed to do, but it appears to clear the screen when I print it out.

To see what I mean, try this code: for string in output: print string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!