I need to display the ip address after address: . Everything else needs to be trimmed. What code will most optimally solve my problem?
show interface PPPoE0
id: PPPoE0
index: 0
type: PPPoE
description: Internet (NetFriend)
interface-name: PPPoE0
link: up
connected: yes
state: up
mtu: 1400
tx-queue: 1000
address: 46.42.50.121
mask: 255.255.255.255
global: yes
defaultgw: yes
priority: 1000
security-level: public
auth-type: PAP, CHAP, MS-CHAP, MS-CHAPv2
remote: 46.42.48.1
uptime: 45562
session-id: 23430
fail: no
via: GigabitEthernet0/Vlan2
last-change: 45562.183918
(config)> exit
Core::Configurator: Bye.
CodePudding user response:
You can use a simple Regular Expression to search for all matching IPs in a string.
The regex query for an IP Adress would be : (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})
If you want to learn what the RegEx query does you can see the full explanation here.
The code would look something like
import re
text = """
show interface PPPoE0
id: PPPoE0
index: 0
type: PPPoE
description: Internet (NetFriend)
interface-name: PPPoE0
link: up
connected: yes
state: up
mtu: 1400
tx-queue: 1000
address: 46.42.50.121
mask: 255.255.255.255
..................
"""
regex_pattern_ip = re.compile(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')
ip = regex_pattern_ip.search(text)[0]
print(ip)
Hope this helped
CodePudding user response:
I don't know about most optimal, but one way to do it is to split by lines, find the one containing address, and extract the text from it:
def getIp(text):
lines = text.split("\n")
for line in lines:
line = line.replace(" ").replace("\t")#in case it has newlines or spaces in front, not sure based off question
if line.startswith("address:"):
return line[8:]
raise Exception("Address line not found")
CodePudding user response:
Maybe not optimal, but will work:
print(s[s.find("address: ") 9: s.find("mask")].strip())