프로그램/python

[python] 텍스트 파일에서 IP을 추출하여 저장하기

더월드 2023. 8. 11.

Python으로 특정 경로의 파일에서 IP 주소를 추출하여 파일로 저장하는 코드입니다.

 

우선 특정 파일에서 IP을 추출하는 함수를 만들어 보겠습니다.

 

IP를 나타내는 정규식 표현은 아래와 같고

ip_regex = r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b"

 

이를 해석하면

\b : 단어 경계
[0-9]{1,3} : 길이가 1~3인 숫자
(?:[0-9]{1,3}\.){3} : 끝에 점(.)이 있는 1~3 길이의 숫자를 3번 입력(예: 194.208.15.)

 

파일을 열어서 패턴이 일치하면 ips에 저장

re.findall( 패턴, 읽은 파일 내용)

: findall()은 정규식과 매치되는 모든 문자열을 리스트형식으로 리턴한다.

 

저장방법 : ips에 extend 함수로 계속 추가한다.

#--------------------------
# IP 추출
#--------------------------
def extract_ips_from_file(file_path):
    ips = []
    ip_regex = r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b"

    with open(file_path, 'r') as file:
        contents = file.read()
        matches = re.findall(ip_regex, contents)
        ips.extend(matches)

    return ips

with open(file_path, 'r') as file: 이렇게 파일을 읽을경우, chcp949, utf-8 등에 문자 코드에 따라서 에러가 발생할 수 있다.

에러 유형:

"UnicodeDecodeError: 'cp949' codec can't decode byte 0xed in position 10: illegal multibyte sequence" 이런 에러는

cp949로 코딩된 파일을 읽었을때 발생하는데, 

 

open('파일경로', 'rt', encoding='UTF8') 이런식으로 문자 엔코딩을 맞춰서 해결하는 방법도 있지만,

실제로 해보면 에러가 해결이 안될때가 있다.

 

이럴때 그냥, errors='ignore' 옵션을 주면 된다.

with open(file_path, 'r', errors='ignore') as file:

#--------------------------
# IP 추출
#--------------------------
def extract_ips_from_file(file_path):
    ips = []
    ip_regex = r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b"

    with open(file_path, 'r', errors='ignore') as file:
        contents = file.read()
        matches = re.findall(ip_regex, contents)
        ips.extend(matches)

    return ips

 

추출한 ips을 output_file_path에 저장하는 함수는 아래와 같다.

#--------------------------
# 결과 저장
#--------------------------
def save_ips_to_file(ips, output_file_path):
    with open(output_file_path, 'w') as file:
        for ip in ips:
            file.write(ip + '\n')

 

아래 코드는 위 `extract_ips_from_file` 함수를 사용하여

지정된 파일(E:/Work/test_log.txt)에서 IP 주소를 추출하고,

`save_ips_to_file` 함수를 사용하여 추출된 IP 주소를 지정된 경로의 파일(E:/Work/ip_export.txt)에 저장합니다.

 

`input_file_path` 변수에 입력 파일의 경로를,

`output_file_path` 변수에 IP 주소가 저장될 파일의 경로를 지정해야 합니다.

import re

#--------------------------
# 설정
#--------------------------
input_file_path = 'E:/Work/test_log.txt'
output_file_path = 'E:/Work/ip_export.txt'

#--------------------------
# Main
#--------------------------
if __name__ == "__main__":
	ips = extract_ips_from_file(input_file_path)
	save_ips_to_file(ips, output_file_path)

 

 

전체 소스 코드는 아래와 같다.

# -*- coding: utf-8 -*-
import re

#--------------------------
# 설정
#--------------------------
input_file_path = 'E:/Work/test_log.txt'
output_file_path = 'E:/Work/ip_export.txt'
    
#--------------------------
# IP 추출
#--------------------------
def extract_ips_from_file(file_path):
    ips = []
    ip_regex = r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b"

    with open(file_path, 'r', errors='ignore') as file:
        contents = file.read()
        matches = re.findall(ip_regex, contents)
        ips.extend(matches)

    return ips

#--------------------------
# 결과 저장
#--------------------------
def save_ips_to_file(ips, output_file_path):
    with open(output_file_path, 'w') as file:
        for ip in ips:
            file.write(ip + '\n')

#--------------------------
# Main
#--------------------------
if __name__ == "__main__":
	ips = extract_ips_from_file(input_file_path)
	save_ips_to_file(ips, output_file_path)

 

 test를 위해서 test_log.txt 파일을 임으로 생성하고,

1
2
33
테스트 ip 추출
123.111.222.33
정말로 IP 추출가능?
111.222.0.12
가
나다라
1111-2222-3333
1.2.3.4
192.168.0.1
100.200.1.2

 

>python ip_export.py 를 실행하면,

아래와 같이 ip_export.txt 결과물을 얻을 수 있다.

 

○ 생성된 ip_export.txt 파일 내용

123.111.222.33
111.222.0.12
1.2.3.4
192.168.0.1
100.200.1.2

 

댓글

💲 추천 글