Search This Blog

Saturday 16 January 2021

Python regex to extract IP addresses from text file

 If you need to extract IP Addresses from a text file with thousands or even millions of lines of text and you have something better to do than do this manually, the below script is your friend.

Device IP Address=        Not really regex, just simple text finding

(?P<NAS>\w+\.\w+\.\w+\.\w+)    This is where it becomes interesting. <NAS> is creating s a variable for the IP Address matched by the regex. \w+ matches any word character (equal to [a-zA-Z0-9_])

import re
for line in open("acs-logs-concatenated.txt""r"):
    m = re.compile("Device IP Address=(?P<NAS>\w+\.\w+\.\w+\.\w+)")
    print(re.findall(m, line))

No comments:

Post a Comment

Nornir Compliance Check