这是一个示例文本:
Jan 1 11:22:33 DHCPDISCOVER from 00:11:22:33:44:55
Jan 1 11:22:34 DHCPOFFER on 10.0.0.5 to 00:11:22:33:44:55
Jan 1 11:22:35 DHCPREQUEST for 10.0.0.5 from 00:11:22:33:44:55
Jan 1 11:22:36 DHCPACK on 10.0.0.5 to 00:11:22:33:44:55
Jan 1 11:22:37 DHCPNACK on 10.0.0.5 to 00:11:22:33:44:55
我想提取特定 mac 地址的首次注册日期和时间以及上次注册的时间。
输出必须如下所示:
for the given mac address: 00:11:22:33:44:55
Start: Jan 1 11:22:33
End: Jan 2 22:33:44
问:我想要...为。。。呸......首次注册...最后...注册。
你想要这样的东西:
mac_dict = {}
for line in in_file:
words = line.split(' ')
if words[3] == 'DHCPACK':
mac = words[-1]
datetime = ' '.join(words[:3])
if not mac in mac_dict:
mac_dict[mac] = {'first_date':datetime, 'last_date': None}
else:
mac_dict[mac]['last_date'] = datetime
for mac in mac_dict:
print("for the given mac address: {}nStart:{m[first_date]}nEnd:{m[last_date]}".format(mac, m=mac_dict[mac]))
#read file
file = open ("test.txt", "r")
lines = file.readlines()
file.close()
#nullpoint
DHCPDISCOVER = 0
DHCPOFFER= 0
DHCPREQUEST= 0
DHCOPACK= 0
DHCPACK= 0
start=0
end=0
#Input MAC from user
mac=str (input("For what MAC address do you want to parse: "))
#Capture date respectively to MAC
import re
y=[]
for line in lines:
if line.find(mac) !=-1:
ip = re.findall ('d{1,3}.d{1,3}.d{1,3}.d{1,3}', line)
date = re.findall (r'w{3}sd{1,2}sd{2}:d{2}:d{2}', line)
y.append(date[0])
#find the keywords
for line in lines:
if line.find ("DHCPDISCOVER") != -1 and line.find(mac) !=-1:
DHCPDISCOVER=+1
if line.find ("DHCPOFFER") != -1 and line.find(mac) !=-1:
DHCPOFFER=+1
if line.find ("DHCPREQUEST") != -1 and line.find(mac) !=-1:
DHCPREQUEST=+1
if line.find ("DHCOPACK") != -1 and line.find(mac) !=-1:
DHCOPACK=+1
if line.find ("DHCPACK") != -1 and line.find(mac) !=-1:
DHCPACK=+1
#display results
print ("Start: ", min(y))
print ("End: ", max(y))
print ("MAC: ", mac)
print ("DHCPDISCOVER: ",DHCPDISCOVER,"x")
print ("DHCPOFFER: ",DHCPOFFER,"x")
print ("DHCPREQUEST: ",DHCPREQUEST,"x")
print ("DHCOPACK: ",DHCOPACK,"x")
print ("DHCPACK: ",DHCPACK,"x")