Python - 从输出中获取值

时间:2017-10-27 13:47:37

标签: python output paramiko

我正在使用我的.send和.recv中的paramiko模块运行python脚本 我有这个输出

crypto map OUTSIDEMAP 10 match address XXXXXXXXXXX
crypto map OUTSIDEMAP 20 match address XXXXXXXXXXX
crypto map OUTSIDEMAP 21 match address XXXXXXXXXXX
crypto map OUTSIDEMAP 23 match address XXXXXXXXXXX
crypto map OUTSIDEMAP 25 match address XXXXXXXXXXX
crypto map OUTSIDEMAP 26 match address XXXXXXXXXXX
crypto map OUTSIDEMAP 27 match address XXXXXXXXXXX
crypto map OUTSIDEMAP 430 match address XXXXXXXXXXX
crypto map OUTSIDEMAP 550 match address XXXXXXXXXXX
crypto map OUTSIDEMAP 660 match address XXXXXXXXXXX
crypto map OUTSIDEMAP 800 match address XXXXXXXXXXX

我需要在OUTSIDEMAP(10,20,21等)之后获取数值。我尝试过拆分方法,但显示的行数随时都可以改变,所以我不会这样做。 t有固定列表值位置。

有什么想法吗?

代码

#!/usr/bin/env python

import paramiko
import time

# Variables
host = xxxxxx = 'xxxxxx'

# Create instance of SSHClient object
ssh = paramiko.SSHClient()

# Automatically add untrusted hosts
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Automatically add untrusted hosts
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# initiate SSH connection
ssh.connect('xxxxxx', port=22, username='xxxxx', password='xxxxx', look_for_keys=False, allow_agent=False)
print "SSH COnnection established with %s" % host

# Use invoke_shell to establish an 'interactive session'
ssh_conn = ssh.invoke_shell()
print "Interactive SSH session established"

print "Give the name of the 3PPartner\n"
partner = raw_input('>')

# Commands prompted
ssh_conn.send('\n')
ssh_conn.send('enable\n')
time.sleep(.5)
ssh_conn.send('xxxxxxxn')
time.sleep(.5)
ssh_conn.send("terminal pager 0\n")
time.sleep(.5)
ssh_conn.send('show running-config crypto map | i ' + str(partner) + '\n')
time.sleep(1)
output = ssh_conn.recv(65535)

# Edit output
c_map = output.split(' ')
print c_map[25]
print c_map[31]
print c_map[37]


# Close session
ssh.close()
print 'Logged out of device %s' %host

1 个答案:

答案 0 :(得分:0)

它始终是OUTSIDEMAP之后的字段吗?如果是这样,你对split()的想法可能会这样:

output = "crypto map OUTSIDEMAP 23 match address XXXXXXXXXXX"
outputList = output.split(" ")

index = outputList.index("OUTSIDEMAP")

if index > -1:
    numValue = outputList[index+1]
    print(numValue)

输出:

23

编辑:

如果它的一个长串,你可以使用:

output = "crypto map OUTSIDEMAP 10 match address XXXXXXXXXXX\
crypto map OUTSIDEMAP 20 match address XXXXXXXXXXX\
crypto map OUTSIDEMAP 21 match address XXXXXXXXXXX\
crypto map OUTSIDEMAP 23 match address XXXXXXXXXXX"


outputList = output.split(" ")
indices = [i for i, x in enumerate(outputList) if x == "OUTSIDEMAP"]

print([outputList[x+1] for x in indices])

输出:

['10', '20', '21', '23']

枚举形成索引和值的列表元组。与[(0,"crypto"),(1, "map)...]类似,如果i的值为x,则列表理解会使用OUTSIDEMAP填充列表,以便您获得包含OUTSIDEMAP出现的索引的列表。然后在其中添加1以获取之后的字段,其中包含您要查找的数字。

或者使用正则表达式:

print(re.findall("OUTSIDEMAP (\d+) match",output))

输出:

['10', '20', '21', '23']