应用场景:公司给蓝队人员一个解封IP列表,假如某个IP满足属于某某C段,则对该IP进行解封。该脚本则是进行批量筛选出符合条件的白名单IP
实操如下:公司给了一个已经封禁了的黑名单IP列表如下(black)
公司要求对满足这些段的IP进行解封(white)
脚本如下
import ipaddress
def is_ip_in_subnet(ip: str, subnet: str) -> bool:
ip_obj = ipaddress.ip_address(ip)
subnet_obj = ipaddress.ip_network(subnet, strict=False)
return ip_obj in subnet_obj
def read_txt_to_array(file_path: str):
try:
with open(file_path, 'r', encoding='utf-8') as file:
lines = file.readlines()
return [line.strip() for line in lines]
except Exception as e:
print(f"读取文件时出错: {e}")
return []
if __name__ == "__main__":
white = read_txt_to_array("white.txt")
black = read_txt_to_array("black.txt")
for subnet in white:
for ip_to_check in black:
if is_ip_in_subnet(ip_to_check, subnet):
print(f"IP地址 {ip_to_check} 属于 {subnet}")
else:
continue
使用过程如下
将黑名单ip放在black.txt中,将白名单ip放在white.txt中
运行main.py即可 效果如下