Python 脚本扫描网络并获取活动主机 IP 和 MAC 地址
Python 脚本扫描网络并获取活动主机 IP 和 MAC 地址
该脚本使用 subprocess 模块执行系统命令,首先执行 nmap 命令扫描网络并获取活动主机列表,然后使用 arp 命令获取每个主机的 MAC 地址,并将结果输出到屏幕和文件中。注意,执行 sudo 命令需要输入管理员密码。
import subprocess
def scan_network(ifname):
# 执行 nmap 命令扫描网络
cmd = f"sudo nmap -sP -n {ifname} | grep 'Nmap scan report' | awk '{{print $5}}""
result = subprocess.check_output(cmd, shell=True)
# 将结果转换为字符串列表
hosts = result.decode().strip().split('\n')
return hosts
# 扫描网络并获取活动主机列表
active_hosts = scan_network('wlan0')
# 输出活动主机的 IP 地址和 MAC 地址
for host in active_hosts:
cmd = f"sudo arp -n | grep {host}"
result = subprocess.check_output(cmd, shell=True)
mac = result.decode().split()[2]
print(f"IP 地址: {host},MAC 地址: {mac}")
# 将活动主机的 IP 地址和 MAC 地址保存到文件中
with open('active_hosts.txt', 'w') as f:
for host in active_hosts:
cmd = f"sudo arp -n | grep {host}"
result = subprocess.check_output(cmd, shell=True)
mac = result.decode().split()[2]
f.write(f"IP 地址: {host},MAC 地址: {mac}\n")
原文地址: https://www.cveoy.top/t/topic/jnbS 著作权归作者所有。请勿转载和采集!