Python网络扫描脚本调试:活动主机未保存到文件

在使用以下Python代码进行网络扫描并保存记录时,我遇到了一个问题,即活动主机的IP地址和MAC地址没有被保存到文件中:

def scan_network(ifname):
    active_hosts = {}
    for i in range(1, 255):
        dst_ip = '192.168.197.' + str(i)
        send_arp_request(ifname, '192.168.197.1', get_mac_address(ifname), dst_ip)
        time.sleep(0.1)
        response = send_arp_reply(ifname, dst_ip, get_mac_address(ifname), '192.168.197.1', get_mac_address(ifname))
        if response is not None:
            active_hosts[response['src_ip']] = response['src_mac']
    return active_hosts

def save_records():
    active_hosts = scan_network(ifname)
    with open('records.txt', 'w') as f:
        f.write('活动主机IP地址\t\tMAC地址\n')
        for ip, mac in ip_mac_dict.items():
            f.write(ip + '\t' + mac + '\n')
        f.write('\n攻击源IP地址\t\tMAC地址\n')
        for ip, mac in attack_source_dict.items():
            f.write(ip + '\t' + mac + '\n')
        f.write('\nICMP Flood攻击:' + detect_icmp_flood() + '\n')
        f.write('TCP攻击:' + detect_tcp_attack() + '\n')
        f.write('ARP欺骗攻击:' + detect_arp_spoofing() + '\n')
        f.write('')

问题: 为什么活动主机的IP地址和MAC地址并没有保存到文件中?

原因: 问题出在save_records函数中第一个for循环使用的字典名称错误。它使用了ip_mac_dict字典,而实际上应该使用active_hosts字典。

解决方案: 将第一个for循环修改为以下代码即可解决问题:

for ip, mac in active_hosts.items():
    f.write(ip + '\t' + mac + '\n')

通过将字典名称更正为active_hosts,现在可以成功地将扫描到的活动主机的IP地址和MAC地址保存到records.txt文件中了。


原文地址: https://www.cveoy.top/t/topic/jm8W 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录