如何用Python代码实现是否为正常主机其ARP表中没有被篡改为伪MAC地址或者是伪IP地址
要实现这个功能,需要分别检查主机的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地址
原文地址: http://www.cveoy.top/t/topic/fyOW 著作权归作者所有。请勿转载和采集!