Search code examples
pythonpython-3.xsshpexpect

The output is not displayed correctly formatted when i get output with ssh connection remotely with python script


I connect to remote server with ssh with my python codes. I connect and get results. But results are coming with \r\n My codes are below :

#To connect remote server and run networkmon.py and get results
from pexpect import pxssh
import getpass
try:
    s = pxssh.pxssh()
    hostname = "10.89.71.39"
    username = "manoadmin"
    password = "********" #generic pass added
    s.login(hostname, username, password)
    s.sendline('cat manobackup_scripts/networkmon.py')
    s.prompt()
    print(s.before)
    s.logout()
except pxssh.ExceptionPxssh as e:
    print("pxssh login hata.")

The output i get is like;

import os\r\nimport socket\r\n\r\nimport time\r\n\r\nstart_time = time.time()\r\n\r\n

But i want the out put to be printed out as below

import os import socket

import time

start_time = time.time()


Solution

  • By default data in s.before is of bytes, not str. You can decode when printing:

    print(s.before.decode() )
    

    You can ask it to automatically convert the data to str by specifying an encoding:

    s = pxssh.pxssh(encoding='utf8')
    ...
    print(s.before)