Python 代码检测主机 ARP 表是否被篡改
要实现这个功能,需要分别检查主机的 ARP 表中的 MAC 地址和 IP 地址是否与其真实地址匹配。可以使用 Python 的 socket 和 subprocess 模块来实现。
首先,获取主机的真实 MAC 地址和 IP 地址:
import socket
import subprocess
def get_mac_address():
# 获取 MAC 地址
output = subprocess.check_output(["ifconfig"])
output = output.decode("utf-8")
mac_address = re.search(r"ether\s([0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5})", output).group(1)
return mac_address
def get_ip_address():
# 获取 IP 地址
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip_address = s.getsockname()[0]
s.close()
return ip_address
然后,获取主机的 ARP 表:
def get_arp_table():
# 获取 ARP 表
output = subprocess.check_output(["arp", "-a"])
output = output.decode("utf-8")
arp_table = {}
for line in output.split("\n"):
if line.strip() != "":
ip_address, mac_address = re.findall(r"(\d+\.\d+\.\d+\.\d+)\s+([0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5})", line)[0]
arp_table[ip_address] = mac_address
return arp_table
最后,检查 ARP 表中的 MAC 地址和 IP 地址是否与主机的真实地址匹配:
def is_normal_host():
mac_address = get_mac_address()
ip_address = get_ip_address()
arp_table = get_arp_table()
if arp_table[ip_address] != mac_address:
return False
for ip, mac in arp_table.items():
if ip != ip_address and mac != 'ff:ff:ff:ff:ff:ff' and mac != mac_address:
return False
return True
这个函数返回 True 表示主机是正常的,返回 False 表示主机的 ARP 表中存在被篡改的 MAC 地址或 IP 地址。
原文地址: https://www.cveoy.top/t/topic/joFg 著作权归作者所有。请勿转载和采集!