Question

I'm using following script to run some commands in a shell. The basic scenario is, I've one server application, to which I can connect through remote shell using ssh command. I'm mimicking this using paramiko, but the problem is whe I run the following script -

import sys
#sys.stderr = open('/dev/null')       # Silence silly warnings from paramiko
import paramiko as pm
from paramiko import AutoAddPolicy
sys.stderr = sys.__stderr__
import os

class AllowAllKeys(pm.MissingHostKeyPolicy):
    def missing_host_key(self, client, hostname, key):
        return

HOST = 'localhost'
USER = 'admin'
PASSWORD = 'admin'

client = pm.SSHClient()
#client.load_system_host_keys()
#client.load_host_keys(str(pm.AutoAddPolicy()))
client.set_missing_host_key_policy(pm.AutoAddPolicy())
client.connect(HOST, username=USER, password=PASSWORD, port=2222)

channel = client.invoke_shell()
stdin = channel.makefile('wb')
stdout = channel.makefile('rb')

stdin.write('''
cd /Realms
exit
''')

for line in stdout:    
    print line.strip('\n')

stdout.close()
stdin.close()
client.close()

The execution of this shows lot of bad characters as follows -

←[39m←[1madmin←[0m@pjajoo-t420:/>
←[39m←[1madmin←[0m@pjajoo-t420:/> cd /Realms
←[39m←[1madmin←[0m@pjajoo-t420:/Realms> exit

Can anybody help me strip these bad characters, so that it will helpful for my debugging and answer verification purposes?

Note: I'm using Windows 7.

Was it helpful?

Solution

Answer can be found at - How can I remove the ANSI escape sequences from a string in python

I've used following lines of code for the above code and it worked for me -

import re

for line in stdout:
    print (re.compile(r'\x1b[^m]*m')).sub('', line)

It removed all the bad characters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top