Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python get list of mac addresses and compare them with list from file

I am a beginner in Python and I hope you can help me solve this problem.

I have a list of mac addresses written in a file. I need to get the list of mac addresses on the network, compare them with the addresses from the file and then print in stdout the addresses from the file that are not found in the list of addresses from the network.

And in the end update the file with those addresses.

For now I managed to read a file that I give as an argument:

import sys

with open(sys.argv[1], 'r') as my_file:
   lines = my_file.read()

my_list = lines.splitlines()

I am trying to read the mac addresses by running the process arp from python:

import subprocess

addresses = subprocess.check_output(['arp', '-a'])

But with this code I get this:

  Internet Address      Physical Address      Type
  156.178.1.1           5h-c9-6f-78-g9-91     dynamic
  156.178.1.255         ff-ff-ff-ff-ff-ff     static
  167.0.0.11            05-00-9b-00-00-10     static
  167.0.0.123           05-00-9b-00-00-ad     static
  .....

How can I filter here so I can get only the list of mac addresses?

Or can I check the two lists like this to see if a mac address from the file is on the network and if not to print it out?

like image 947
schmimona Avatar asked Nov 17 '15 19:11

schmimona


2 Answers

Starting with what you have:

networkAdds = addresses.splitlines()[1:]
networkAdds = set(add.split(None,2)[1] for add in networkAdds if add.strip())
with open(sys.argv[1]) as infile: knownAdds = set(line.strip() for line in infile)

print("These addresses were in the file, but not on the network")
for add in knownAdds - networkAdds:
    print(add)
like image 177
inspectorG4dget Avatar answered Oct 28 '22 12:10

inspectorG4dget


To fetch MAC address you can use this regular expression:

import re

addresses = """  Internet Address      Physical Address      Type
156.178.1.1           5f-c9-6f-78-f9-91     dynamic
156.178.1.255         ff-ff-ff-ff-ff-ff     static
167.0.0.11            05-00-9b-00-00-10     static
167.0.0.123           05-00-9b-00-00-ad     static
....."""

print(re.findall(('(?:[0-9a-fA-F]{1,}(?:\-|\:)){5}[0-9a-fA-F]{1,}'),addresses))

Output:

['5f-c9-6f-78-f9-91', 'ff-ff-ff-ff-ff-ff', '05-00-9b-00-00-10', '05-00-9b-00-00-ad']

As far as I can see your MAC-adresses are not following naming convention used in this regexp, so it is up to you to play with [0-9a-fA-F] thing.

like image 22
Alex Bogomolov Avatar answered Oct 28 '22 12:10

Alex Bogomolov