hopefully this is a quick an easy on! I am trying to do a search for a hostname on a device and then use that hostname to dictate the config that is sent to it via netmiko. I think I'm failing because the output is not on one line. As a test at the moment I am just trying to print the output as follows:
device_name = net_connect.send_command('show running-config sys global-settings hostname')
hostname = re.search('^hostname', device_name, re.M)
print(hostname)
When I run the above command on the device manually the output is like this:
sys global-settings {
hostname triton.lakes.hostname.net
}
So do I need to adjust the re.search to take into account the seperate lines to just capture the 'hostname triton.lakes.hostname.net' line?
Many thanks
(?=...)
Matches if ... matches next, but doesn’t consume any of the string. This is called a lookahead assertion. For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov'.
(?<=...)
Matches if the current position in the string is preceded by a match for ... that ends at the current position. This is called a positive lookbehind assertion. (?<=abc)def will find a match in 'abcdef', since the lookbehind will back up 3 characters and check if the contained pattern matches.
Demo:
(?<={).*(?=})
It means to match strings beginning with
{
and ending with}
import re
s = """
sys global-settings {
hostname triton.lakes.hostname.net
}
"""
print(re.search(r"(?<={)\s+(hostname .+?)\s+(?=})", s).group(1))
# hostname triton.lakes.hostname.net