How to print output of pexpect consisting 'r' in next line of the terminal?

Question:

I have the follwoing code snippet from a pexpect script

import pexpect
import time
username=<username>
password=<password>
child = pexpect.spawn('ssh <username>@192.168.1.219',timeout=40)
child.expect(['MyUbuntu','$','#'])
child.sendline(<password>)
child.expect(['MyUbuntu','$','#'])
time.sleep(2)
child.sendline('execute ping 192.168.1.2')
child.expect(['MyUbuntu','$','#'])
k=child.before
k=k.splitline
for line in k:
    print(line)

However it gives me an output as follows:

b' execute ping 192.168.1.2rrnPING 192.168.1.2: 56 data bytesrn64 bytes from 192.168.1.2: icmp_seq=0 ttl=62 time=0.2 msrn64 bytes from 192.168.1.2: icmp_seq=1 ttl=62 time=0.2 msrn64 bytes from 192.168.1.2: icmp_seq=2 ttl=62 time=0.2 msrn64 bytes from 192.168.1.2: icmp_seq=3 ttl=62 time=0.2 msrn64 bytes from 192.168.1.2: icmp_seq=4 ttl=62 time=0.1 msrnrn--- 192.168.1.2 ping statistics ---rn5 packets transmitted, 5 packets received, 0% packet lossrnround-trip min/avg/max = 0.1/0.1/0.2 msrnrnMyUbuntu '

I want the terminal to show proper readable format of the output with line breaks coming in next line as a normal ping operation would do. How to do that?

Asked By: mrin9san

||

Answers:

You need to decode your binary string.

The encoding to be used may need to be adapted, based on the content of your binary string, but since there are no special characters, I did go with ansi.

b = b' execute ping 192.168.1.2rrnPING 192.168.1.2: 56 data bytesrn64 bytes from 192.168.1.2: icmp_seq=0 ttl=62 time=0.2 msrn64 bytes from 192.168.1.2: icmp_seq=1 ttl=62 time=0.2 msrn64 bytes from 192.168.1.2: icmp_seq=2 ttl=62 time=0.2 msrn64 bytes from 192.168.1.2: icmp_seq=3 ttl=62 time=0.2 msrn64 bytes from 192.168.1.2: icmp_seq=4 ttl=62 time=0.1 msrnrn--- 192.168.1.2 ping statistics ---rn5 packets transmitted, 5 packets received, 0% packet lossrnround-trip min/avg/max = 0.1/0.1/0.2 msrnrnMyUbuntu '
s = b.decode("ansi")
print(s)

Output:

 execute ping 192.168.1.2
PING 192.168.1.2: 56 data bytes
64 bytes from 192.168.1.2: icmp_seq=0 ttl=62 time=0.2 ms 
64 bytes from 192.168.1.2: icmp_seq=1 ttl=62 time=0.2 ms 
64 bytes from 192.168.1.2: icmp_seq=2 ttl=62 time=0.2 ms 
64 bytes from 192.168.1.2: icmp_seq=3 ttl=62 time=0.2 ms 
64 bytes from 192.168.1.2: icmp_seq=4 ttl=62 time=0.1 ms 

--- 192.168.1.2 ping statistics ---
5 packets transmitted, 5 packets received, 0% packet loss
round-trip min/avg/max = 0.1/0.1/0.2 ms

MyUbuntu
Answered By: Mike Scotty
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.