2011-12-11 5 views
1

저는 파이썬을 처음 접했고 정규식으로 로그 파싱에 대한 자습서를 진행했습니다. 아래 코드에서 로그를 구문 분석하고 원격 IP가 서버에 연결하여 파일을 만들 수 있습니다. 내가 만든 out.txt 파일에서 중복 IP를 제거 할 부분이 없습니다. 감사IP를위한 파이썬 로그 구문 분석

import re 
import sys 

infile = open("/var/log/user.log","r") 
outfile = open("/var/log/intruders.txt","w") 

pattern = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" 
regexp = re.compile(pattern, re.VERBOSE) 

for line in infile: 
    result = regexp.search(line) 
    if result: 
    outfile.write("%s\n" % (result.group())) 

infile.close() 
outfile.close() 

답변

5

당신은 결과가 set()에서 지금까지 본 및 아직 보지되지 않은 만 쓰기 아웃 결과를 저장할 수 있습니다. 이 논리는 기존 코드에 쉽게 추가 할 수 있습니다.

import re 
import sys 

seen = set() 

infile = open("/var/log/user.log","r") 
outfile = open("/var/log/intruders.txt","w") 

pattern = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" 
regexp = re.compile(pattern, re.VERBOSE) 

for line in infile: 
    mo = regexp.search(line) 
    if mo is not None: 
    ip_addr = mo.group() 
    if ip_addr not in seen: 
     seen.add(ip_addr) 
     outfile.write("%s\n" % ip_addr) 

infile.close() 
outfile.close()