1. 背景
马上有电子政务外网攻防演练要处理ip
2. 脚本1
生成c段和连续c段所有ip地址.py
用处:生成单一c段或者连续c段范围内的所有ip地址。
用法:ipc.txt 放入 ip段或者两个ip段范围:如:
192.168.3.0/24
172.16.1.0/24-172.16.3.0/24
192.168.1.0/24
结果保存到ip.txt
优缺点:单个c段不会生成.0 和 .255,连续c段范围会生成.0 和 .255 广播地址。
python38 生成c段和连续c段所有ip地址.py:
import ipaddress def generate_ips_from_cidr(cidr): """生成单个CIDR的所有IP地址""" network = ipaddress.ip_network(cidr, strict=False) return [str(ip) for ip in network.hosts()] def generate_ips_from_range(start_cidr, end_cidr): """生成CIDR范围的所有IP地址""" start_network = ipaddress.ip_network(start_cidr, strict=False) end_network = ipaddress.ip_network(end_cidr, strict=False) # 计算CIDR范围的起始和结束IP地址 start_ip = int(ipaddress.IPv4Address(start_network.network_address) + 1) end_ip = int(ipaddress.IPv4Address(end_network.broadcast_address)) # 生成范围内的所有IP地址 all_ips = [] current_ip = start_ip while current_ip <= end_ip: all_ips.append(str(ipaddress.IPv4Address(current_ip))) current_ip += 1 return all_ips def process_cidrs_and_save_unique_ips(input_file, output_file): """处理CIDR和CIDR范围,去重后保存IP地址到文件""" with open(input_file, 'r') as file: lines = file.readlines() all_ips = set() # 使用集合来自动去重 for line in lines: line = line.strip() if '-' in line: # 处理CIDR范围 start_cidr, end_cidr = line.split('-') all_ips.update(generate_ips_from_range(start_cidr, end_cidr)) else: # 处理单个CIDR all_ips.update(generate_ips_from_cidr(line)) # 将去重后的IP地址写入文件 with open(output_file, 'w') as file: for ip in sorted(all_ips): # 对IP地址进行排序 file.write(ip + '\n') print(f"Saved {len(all_ips)} unique IP addresses to {output_file}") # 定义输入和输出文件名
input_file = 'ipc.txt'
output_file = 'ip.txt' # 处理文件并保存结果
process_cidrs_and_save_unique_ips(input_file, output_file)
3. 脚本2
生成范围内C段.py
用处:如果多个c段范围,要自己手工,用的肯定不多,还是为了偷懒。
用法:两个ip段范围:如:
172.16.1.0/24-172.16.3.0/24
192.168.8.0/24-192.168.30.0/24
python38 生成范围内C段.py
import ipaddress def generate_c_blocks(start_cidr, end_cidr): """生成从start_cidr到end_cidr范围内的所有C段""" start_network = ipaddress.ip_network(start_cidr, strict=False) end_network = ipaddress.ip_network(end_cidr, strict=False) c_blocks = [] current_network = start_network while current_network <= end_network: c_blocks.append(str(current_network)) current_network = ipaddress.ip_network(f"{current_network.network_address + 256}/{current_network.prefixlen}", strict=False) return c_blocks def process_cidr_ranges(input_file, output_file): """处理CIDR范围并保存到输出文件""" with open(input_file, 'r') as file: for line in file: line = line.strip() if not line or line.startswith('#'): # 忽略空行和注释行 continue # 假设每行包含一个CIDR范围,用"-"分隔 start_cidr, end_cidr = line.split('-') c_blocks = generate_c_blocks(start_cidr, end_cidr) # 将C段写入输出文件 with open(output_file, 'a') as out_file: for c_block in c_blocks: out_file.write(c_block + '\n') # 调用函数处理ipc.txt文件并将结果保存到ip.txt
process_cidr_ranges('ipc.txt', 'ip.txt')