1. 程式人生 > 其它 >python提取檔案中所有ip

python提取檔案中所有ip

引用正則表示式

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)