Home > Net >  How to print output of pexpect consisting '\r' in next line of the terminal?
How to print output of pexpect consisting '\r' in next line of the terminal?

Time:12-24

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.2\r\r\nPING 192.168.1.2: 56 data bytes\r\n64 bytes from 192.168.1.2: icmp_seq=0 ttl=62 time=0.2 ms\r\n64 bytes from 192.168.1.2: icmp_seq=1 ttl=62 time=0.2 ms\r\n64 bytes from 192.168.1.2: icmp_seq=2 ttl=62 time=0.2 ms\r\n64 bytes from 192.168.1.2: icmp_seq=3 ttl=62 time=0.2 ms\r\n64 bytes from 192.168.1.2: icmp_seq=4 ttl=62 time=0.1 ms\r\n\r\n--- 192.168.1.2 ping statistics ---\r\n5 packets transmitted, 5 packets received, 0% packet loss\r\nround-trip min/avg/max = 0.1/0.1/0.2 ms\r\n\r\nMyUbuntu '

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?

CodePudding user response:

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.2\r\r\nPING 192.168.1.2: 56 data bytes\r\n64 bytes from 192.168.1.2: icmp_seq=0 ttl=62 time=0.2 ms\r\n64 bytes from 192.168.1.2: icmp_seq=1 ttl=62 time=0.2 ms\r\n64 bytes from 192.168.1.2: icmp_seq=2 ttl=62 time=0.2 ms\r\n64 bytes from 192.168.1.2: icmp_seq=3 ttl=62 time=0.2 ms\r\n64 bytes from 192.168.1.2: icmp_seq=4 ttl=62 time=0.1 ms\r\n\r\n--- 192.168.1.2 ping statistics ---\r\n5 packets transmitted, 5 packets received, 0% packet loss\r\nround-trip min/avg/max = 0.1/0.1/0.2 ms\r\n\r\nMyUbuntu '
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
  • Related