Я рекомендую вам использовать переменную ìp
для построения объекта IPAddress[1]
. Затем вы можете вызвать для него метод isPrivate()
или спросить, содержится ли он в IPv4Network
. Это было бы немного более подробным, но общее регулярное выражение, исключающее случайные подсети, заканчивалось бы менее читаемым кодом.
В модифицированном фрагменте я также изменил одну строку, которая мне кажется ошибкой (это там комментируется).
import re
from ipaddress import IPv4Address
fh = 'ips.txt'
fh2= open ('filtereds.txt', 'w')
ip_regex = re.compile(r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})")
with open (fh, "r") as myfile:
data=myfile.readlines()
for line in data:
line = line.strip()
match = ip_regex.findall(line)
if match:
for (ip) in match:
ipaddress = IPv4Address(ip)
if ipaddress.is_global: # and other criterias
# print('\n'.join(match), file=fh2) this would print all the line (with other IPs that does not fit criteria)
print(ip, file=fh2) #this would print only the matched IP
else:
pass