1 #! python3 2 # coding=utf-8 3 # @Time : 2018/6/15 15:03 4 # @Author : hsq 5 # @File : IPCatcher.py 6 # @Software: PyCharm 7 8 """ 9 捕获文本中的IP 10 【输入】带IP混合文本的文件 11 【输出】捕获出来的IP,去重,每行显示一个 12 【使用】 13 输入文件放res_in目录 14 输出文件放res_out目录 15 """ 16 17 import os 18 import re 19 import sys 20 from PyInstaller.compat import FileNotFoundError, FileExistsError 21 22 # 读取文件 23 # 错误备忘 :无法识别python当前运行目录 24 # input_floder_root_path = os.path.abspath('.')+"\res_in\" # 输入文件夹 25 # output_floder_root_path = os.path.abspath('.')+"\res_out\" # 输出文件夹 26 output_file = "output_result.txt" 27 output_str_list = [] 28 29 30 # 获取当前运行目录 31 def get_current_path(): 32 paths = sys.path 33 current_file = os.path.basename(__file__) 34 for path in paths: 35 try: 36 if current_file in os.listdir(path): 37 return path 38 except (FileExistsError,FileNotFoundError) as e: 39 print(e) 40 41 input_floder_root_path = get_current_path()+"\res_in\" # 输入文件夹 42 output_floder_root_path = get_current_path()+"\res_out\" # 输出文件夹 43 44 print (input_floder_root_path) 45 46 # 读取文件夹 # 定位目标 # 解析目标 # 存储目标 47 for file in os.listdir(input_floder_root_path): 48 with open(input_floder_root_path+file, 'r',encoding='utf-8') as f:#错误备忘:读取字节流和re解析错误 49 for line in f.readlines(10240000): # 关键点:缓存大小为B,每次读取10MB,防止占用内存过大 50 # 关键点:过滤IP,有效性检查,数值显示检查去除补0 51 for ip in re.findall( 52 # """ 正则表达式 53 # (?<!) 不匹配之前,开始匹配 54 # (?!) 不匹配之后,开始匹配 55 #错误备忘:(未过滤01. 001. 000.) 56 # r'(?<![.d])(?:25[0-5].|2[0-4]d.|[01]?dd?.){3}(?:25[0-5]|2[0-4]d|[01]?dd?)(?![.d])', 57 # """ 58 r'(?<![.d])(?:2[0-5][0-5].|1[d][d].|[1-9][d].|[d].){3}(?:2[0-5][0-5]|1[d][d]|[1-9][d]|[d])(?![.d])', 59 line): 60 output_str_list.append(ip) 61 62 output_str_list = list(set(output_str_list)) # 关键点:去重 63 for ip in sorted(output_str_list): 64 print (ip) 65 print ('list len:',output_str_list.__len__()) 66 print ('list final:',output_str_list) 67 68 # 生成文件 69 with open(output_floder_root_path+output_file, 'w+') as f: 70 for line in output_str_list: 71 f.writelines(line+' ')