I have this string below, from which I need to get specific configuration for respective interfaces, example I need to be able to parse to get.
interface Loopback0
ip address 1.1.1.1/32
no shutdown
isis enable 2222
isis passive
or be able to get
interface Management0
no sflow enable
ip address 1.1.1.2/31
no shutdown
isis enable 2222
isis passive
The number of lines under an interface can vary.
The string is:
[hostname router\r\n!\r\ninterface Loopback0\r\n ip address 1.1.1.1/32\r\n no shutdown\r\n isis enable 2222\r\n isis passive\r\n!\r\nvrf definition MGMT\r\n rd 200:200\r\n!\r\n!\r\nvrf definition VRF_DDOS\r\n rd 2222:100\r\n description VRF_DDOS\r\n!\r\n!\r\n interface ethernet1/1\r\n no sflow enable\r\n ip address 1.1.1.2/31\r\n no shutdown\r\n isis enable 2222\r\n isis passive\r\n!\r\nvrf definition MGMT\r\n rd 200:200\r\n!\r\n!\r\nvrf definition VRF_DDOS\r\n rd 2222:100\r\n description VRF_DDOS\r\n!\r\n!\r\n ]
Checkout https://pythex.org/and learn how to use RegEx
If you enter your string into the exmaple text and use (\\d.\\d.\\d.\\d/\\d\\d) as the pattern it will collect every IP address.
import re
ip_address = re.findall(r'(\d.\d.\d.\d/\d\d)', string)
print(ip_address)
>>> 1.1.1.1/32, 1.1.1.2/31
Alternatively if your output is always the same, you could split the string at '\\' and get the index of each item.
example:
feedback = "[hostname router\r\n!\r\ninterface Loopback0\r\n ip address 1.1.1.1/32\r\n no shutdown\r\n isis " \
"enable 2222\r\n isis passive\r\n!\r\nvrf definition MGMT\r\n rd 200:200\r\n!\r\n!\r\nvrf definition" \
" VRF_DDOS\r\n rd 2222:100\r\n description VRF_DDOS\r\n!\r\n!\r\n interface ethernet1/1\r\n no sflow " \
"enable\r\n ip address 1.1.1.2/31\r\n no shutdown\r\n isis enable 2222\r\n isis passive\r\n!\r\nvrf " \
"definition MGMT\r\n rd 200:200\r\n!\r\n!\r\nvrf definition VRF_DDOS\r\n rd 2222:100\r\n description " \
"VRF_DDOS\r\n!\r\n!\r\n ]".replace('\r\n','').split(' ')
print(feedback[2:6])
output >>> ['Loopback0', 'ip', 'address', '1.1.1.1/32']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.