K.Meleo
K.Meleo

Reputation: 25

Python Scapy wireless scan and match a mac address stored in text file

I have some code that will scan for wireless packets and displays the mac address from each of them. What i would like to do is have a text file of mac addresses and for the code to alert me with a message when one of the addresses in the file is picked up on the wireless scan. I can not think of a way to implement this, here is the code for the wiresless scan and below is an example of the text file.

import sys
from scapy.all import *

devices = set()

def PacketHandler(pkt):
    if pkt.haslayer(Dot11):
        dot11_layer = pkt.getlayer(Dot11)
    
        if dot11_layer.addr2 and (dot11_layer.addr2 not in devices):
            devices.add(dot11_layer.addr2)
            print dot11_layer.addr2

sniff(iface = sys.argv[1], count = int(sys.argv[2]), prn = PacketHandler)

here is example of the text file.

00:11:22:33:44:55
AA:BB:CC:DD:EE:FF

Upvotes: 0

Views: 1379

Answers (1)

Guillaume
Guillaume

Reputation: 2006

Create a function that reads from a .txt and store each line (matching a MAC address) in a list.

def getListMac() -> list: # you can put the path for your .txt file as argument
    with open('MAClist.txt', 'r+') as file:
         res = [x.rstrip('\n') for x in file.readlines()]
    return res

And then check in your packetHandler function if the mac if in this list. Here you have two choice :

  • Call getListMac() at the start of your program, store it in a global variable. Go for this if your .txt file won't change after launching your program.
MACLIST = getListMac()

...
# in your PacketHandler function
if mac in MACLIST:
    print("mac found!") #or whatever your want to do
  • Call the function each time a packet is sniffed. Go for this option if the list of MAC addresses frequently changes and you need it updated when your program is running. Be careful with it as this will slow your program, especially if your list is very long.
# in your PacketHandler function:
     if mac in getListMac():
         print("mac found!") # or whatever your want to do

Finally, i will finish this post by advising you to use a real DBMS, which will be much more efficient than reading a txt file. ;)

EDIT

To answer your comment :

Modify the getListMac function in order to store the information in a dictionnary.

Here is an exemple assuming you use " - " as separator between MAC - Time - Username

def getListMac() -> dict: # you can put the path for your .txt file as argument
    with open('MAClist.txt', 'r+') as file:
         res = {x.rstrip('\n').split(" - ")[0]: x.rstrip('\n').split(" - ")[2] for x in file.readlines()}
    return res

Access the data in the dictionary like this:

if MAC in MACLIST:
    print(f"MAC found -> {MAC}, Username -> {MACLIST[MAC]}")

Upvotes: 1

Related Questions