1

I am trying to use Python Regex to get the IP address from the last line of a log.

I can get an IP if I search through the entire log. For example:

with open("read.log", "r+") as log:
    for line in log:
        address = "^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$"
        match = re.match(address, line)

But when I try to just read the last line and get an IP address, I do not get any results. How do I fix this?

import re

def run():

    try:
        logfile = open('read.log', 'r')
#       print ('First line in log: ',logfile.readline())

        for line in logfile:  
            x = line
            for ip in x:
                address = "^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$"
                match = re.match(address, ip)
                logfile.close   
        print ('Last Line: ', match)


    except OSError as e:
        print (e)

run()

My read.log looks like this...

10.1.177.198 Tue Jun 19 09:25:16 CDT 2018
10.1.160.198 Tue Jun 19 09:25:38 CDT 2018
10.1.177.198 Tue Jun 19 09:25:36 CDT 2018
10.1.177.198 Tue Jun 19 09:26:38 CDT 2018
10.1.177.198 Tue Jun 19 09:27:16 CDT 2018
10.1.177.198 Tue Jun 19 09:28:38 CDT 2018
14
  • You closed logfile too early? (In the for-loop) Commented Jun 19, 2018 at 16:58
  • 1
    for ip in x is iterating over the characters of the line. Commented Jun 19, 2018 at 16:58
  • 1
    Maybe you meant to use x = line.split()? Commented Jun 19, 2018 at 16:59
  • @Barmar Iterate in characters of lines is not necessary for you to do, which re.match has already done for you. Commented Jun 19, 2018 at 17:00
  • Is the IP always the first field? Just use ip = line.split()[0] Commented Jun 19, 2018 at 17:00

1 Answer 1

1

The problem is your regex. ^ matches the beginning of a line, $ the end. If your log lines /only/ had the IP address, your code would work.

>>> import re
>>> m = re.compile("^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$")
>>> m.search('123.123.123.123')
<_sre.SRE_Match object; span=(0, 15), match='123.123.123.123'>

However, that's not the case. The following change will fix your search issue:

>>> import re
>>> m = re.compile("(^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})\s")
>>> m.search('10.1.177.198 Tue Jun 19 09:28:38 CDT 2018').groups()[0]
>>> '10.1.177.198'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.