Home > Enterprise >  Using Regex to define hostname
Using Regex to define hostname

Time:07-05

I am working on a script that looks at the hostname of a device and based on this aplies geographical config. It is currently working using a script I found online.

DEVICE_NAME = net_connect.send_command('show version')
HOSTNAME = re.search(r'(\S )\suptime', DEVICE_NAME, re.M).group(1)

if re.search('ttreda.|tteu. ', HOSTNAME):
    TIMEZONE = 'GMT 0 0'
    SUMMERTIME = 'BST recurring'
else:
    TIMEZONE = 'EST -5 0'
    SUMMERTIME = 'EDT recurring'

But I'd like to make it a bit neater by just using show run | include hostname. I found this search string but it fails

DEVICE_NAME = net_connect.send_command('show run | include hostname')
HOSTNAME = re.search(r'(\S )\shostname', DEVICE_NAME, re.M).group(1)
print(HOSTNAME)

This raises the following exception:

AttributeError: 'NoneType' object has no attribute 'group'

CodePudding user response:

Since hostname will always come before the word you need to extract, you need

match = re.search(r'hostname\s (\S )', DEVICE_NAME)
if match:
    print(match.group(1))

Note it is always better to check if a match occurred before accessing the group(1) value to avoid the AttributeError: 'NoneType' object has no attribute 'group' issue.

Note you do not need the re.M option as it only modifies the behavior of the ^ and $ anchors in the regex, and yours has neither.

  • Related