【发布时间】:2021-01-29 17:26:48
【问题描述】:
好的,所以我和我的同学决定在 python3 中制作一个 macfiler/ids 脚本。我们已经走了很远,但我们被困在一件事上。我们需要扫描无限进行并在找到网络中的新连接时中断,并在新连接被阻止或不被阻止时继续扫描。有人可以帮助我们朝着正确的方向前进吗?
from scapy.all import ARP, Ether, srp
import os
import netifaces
#Ask for the subnet mask and calculate it to CIDR notation
netmask = input("What is the subnetmask of your network? (xxx.xxx.xxx.xxx:)")
CIDR = sum(bin(int(x)).count('1') for x in netmask.split('.'))
#Find the defaultgateway ip
gateways = netifaces.gateways()
default_gateway = gateways['default'][netifaces.AF_INET][0]
#Conversions to make the code easier to read
target_ip = default_gateway + "/" + str(CIDR)
arp = ARP(pdst=target_ip)
ether = Ether(dst="ff:ff:ff:ff:ff:ff")
packet = ether/arp
result = srp(packet, timeout=3, verbose=0)[0]
#Empty list for the found clients in the network
clients = []
#Empty list for the blocked addresses
blockedMac = []
#This needs an infinite loop and break when a new connection is in the network is found
for sent, received in result:
clients.append({'ip': received.psrc, 'mac': received.hwsrc})
#if new connection is found do this
print("Available devices in the network:\n")
print("IP" + " "*18+"MAC")
for client in clients:
print("{:16} {}".format(client['ip'], client['mac']))
blockedConnectionStatus = input("\nWould you like to block a connection? Y/n:")
if blockedConnectionStatus == 'Y' or blockedConnectionStatus == 'y':
macAdress = input("\nEnter the MAC Address to block: \n")
#Open rules.v4 and read if the mac address is allready blocked
with open("/etc/iptables/rules.v4", "r") as f:
data = f.read()
if macAdress.upper() in data:
blockedMac.append(macAdress) #Append the blocked mac address to list blockedMac
print("Allready blocked!")
else:
print(macAdress + " is now being blocked!")
os.system("iptables -A INPUT -p ALL -m mac --mac-source " + macAdress + " -j DROP")
os.system("iptables-save > /etc/iptables/rules.v4")
blockedMac.append(macAdress) #Append the blocked mac address to list blockedMac
#Go back to infinite loop```
【问题讨论】:
标签: python python-3.x while-loop