python提取文件中所有ip

发布于 2022年 05月 19日 13:10

 

引用正则表达式

import re, socket

ip_lists = []
ip_regex = re.compile(
r'(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])'
)
loadpath = input('请输入文件位置:')
loadpath1 = loadpath.replace("'", '').replace('"', '')
with open(loadpath1, 'r') as f:
spam = f.readlines()
for i in spam:
try:
mo = ip_regex.findall(i)
if mo != []:
for ip_info in mo:
ip_real = '.'.join([ip_info[0], ip_info[1], ip_info[2], ip_info[3]])
# print(ip_real)
ip_lists.append(ip_real)
except Exception as e:
pass
lst = list(set(ip_lists))
lst.sort(key=socket.inet_aton)
str = '\n'
new_ip_lst = str.join(lst)
print(new_ip_lst)

exportpath = input('请输入文件保存路径:') + '\\'
exportpath1 = exportpath + input('请输入文件名称(默认txt格式,不需要额外输入):') + '.txt'
with open(exportpath1, 'w', encoding='utf-8') as w:
w.write(new_ip_lst)

推荐文章