我正在尝试使用Python Regex从日志的最后一行获取IP地址。
如果我搜索整个日志,则可以获得IP。例如:
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)
但是,当我尝试仅读取最后一行并获得IP地址时,没有任何结果。我该如何解决?
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()
我的read.log看起来像这样...
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
答案 0 :(得分:1)
问题是您的正则表达式。 ^
匹配行的开头,$
结束。如果您的日志行/ only /具有IP地址,则您的代码将起作用。
>>> 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'>
但是,事实并非如此。以下更改将解决您的搜索问题:
>>> 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'