如何使用python使ssh输出整洁

时间:2018-12-20 13:57:13

标签: python python-3.x

我有一些来自ssh的输出。我想使用python使其整洁

ip_address = "xxxx"
username = "xxx"
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=ip_address,username=username)
remote_connection = ssh_client.invoke_shell() 
remote_connection.send("show run | i _20.20.20.20\n")               
time.sleep(5)
readoutput = remote_connection.recv(65000)
ssh_client.close()

print(readoutput)

现在我得到:

RouterA#show run | i _20.20.20.20
 neighbor 20.20.20.20 remote-as 202025
 neighbor 20.20.20.20 password password
  neighbor 20.20.20.20 activate
crs1.ams1#

在HTML中,我也得到了!

b'\r\nRouterA#show run | i _10.10.10.10\r\n neighbor 10.10.10.10 remote-as 1010\r\n neighbor 10.10.10.10 password password1010\r\n neighbor 10.10.10.10 activate

我想要的是这个((输出中没有\ n)

""""
RouterA#show run | i _20.20.20.20
neighbor 20.20.20.20 remote-as 202025
neighbor 20.20.20.20 password password
neighbor 20.20.20.20 activate
RouterA#

"""

1 个答案:

答案 0 :(得分:0)

那又怎么样:

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

如果是html输出,它是一个字节字符串:

html = b'\r\nRouterA#show run | i _10.10.10.10\r\n neighbor 10.10.10.10 remote-as 1010\r\n neighbor 10.10.10.10 password password1010\r\n neighbor 10.10.10.10 activate'
for line in html.decode().split('\r\n'):
    print(line.strip())

输出:

RouterA#show run | i _10.10.10.10
neighbor 10.10.10.10 remote-as 1010
neighbor 10.10.10.10 password password1010
neighbor 10.10.10.10 activate