ubuntu 如何打印终端下一行包含'\r'的pexpect输出?

zyfwsgd6  于 2022-12-26  发布在  其他
关注(0)|答案(1)|浏览(149)

下面是pexpect脚本中的代码片段

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)

但是,它提供了如下输出:

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 '

我希望终端显示正确的可读格式的输出与换行符来在下一行作为一个正常的ping操作会做什么。如何做到这一点?

djmepvbi

djmepvbi1#

你需要解码你的二进制字符串。
要使用的编码可能需要根据二进制字符串的内容进行调整,但由于没有特殊字符,我使用了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)

输出:

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

相关问题