I am trying to parse the a file content with regular expression as in the code below. If I print the system name inside 'IF' suite, it works. But If I try to do anywhere outside, its throwing name error. Any help would be really appreciated.
#!/usr/bin/python
import re
f=open("cdp-nei1.txt")
f=f.readlines()
for data in f:
cdp_line = data.split("\n")
for line in cdp_line:
if "System Name" in line:
systemname = re.search(r"System Name:(.+)",line)
systemname = systemname.group(1)
print systemname
./show-cdp.py
Router1
#!/usr/bin/python
import re
f=open("cdp-nei1.txt")
f=f.readlines()
for data in f:
cdp_line = data.split("\n")
for line in cdp_line:
if "System Name" in line:
systemname = re.search(r"System Name:(.+)",line)
systemname = systemname.group(1)
print systemname
***
./show-cdp.py
Traceback (most recent call last):
File "./show-cdp.py", line 12, in <module>
print systemname
NameError: name 'systemname' is not defined
File Content (Truncated to show only one block)
Device ID:Router1
System Name: Router1
Interface address(es):
IPv4 Address: 10.0.0.1
Platform: N5K-C5672UP, Capabilities: Router Switch IGMP Filtering Supports-STP-Dispute
Interface: mgmt0, Port ID (outgoing port): Ethernet101/1/47
Holdtime: 179 sec
Version:
Cisco Nexus Operating System (NX-OS) Software, Version 7.0(1)N1(1)
Advertisement Version: 2
Native VLAN: 1
Duplex: full
MTU: 1500
Physical Location: Somewhere,United States
Mgmt address(es):
IPv4 Address: 10.0.0.1