监测局域网内主机的IP、MAC地址的异动变化并记录在Excel表格内

# -*- coding: utf-8 -*-
from scapy.all import *
import time
from openpyxl import load_workbook
import threading,os
R = threading.Lock()    #线程锁
threa_num = 50       #线程数






def get_mac(ip):
    try:
        ans,unans=srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ip),timeout=2,verbose=False)  #发送ARP请求包,verbose=False的话,就不显示发包信息
        for send,rec in ans:
            ip_mac=rec.sprintf("{ARP:%ARP.psrc%-%Ether.src%}")   #将包按照固定的格式打印
            return ip_mac.split("-")[1]
    except Exception as e:
        print("异常对象的类型是:%s"%type(e))
        print("异常对象的内容是:%s"%e)
        return None

def run(ip,row,old_mac):
    global change_list
    global ip_list
    global R

    new_mac = None
    new_mac = get_mac(ip)    #方法一



    print(">>> ",ip,old_mac,new_mac)

    with R:
        old_ip = ""
        if not new_mac == old_mac:
            if not new_mac == None:
                #两次mac不同把记录下来
                for i in ip_list:
                    # print(i,"  ",new_mac,ip_list[i]["old_mac"])
                    if new_mac == ip_list[i]["old_mac"]:
                        old_ip = i
                change_list.append({
                    "old_ip" :old_ip,
                    "new_ip": ip,
                    "old_mac": old_mac,
                    "new_mac":new_mac,
                    "change_date":time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                    "old_index":row
                })
                # print(old_ip,ip,old_mac,new_mac)

if __name__ =='__main__':
    file = "/data/mac_change/MacChange.xlsx"
    wb = load_workbook(file)
    sheet = wb.get_sheet_by_name('Sheet1')
    sheet1 = wb.get_sheet_by_name('mac')
    max_column1 = sheet1.max_row+1
    ip_list = {}
    change_list = []

    for row in range(1,sheet.max_row+1):
        if row == 1:
            continue
        old_mac = sheet.cell(row = row, column = 2).value
        ip = sheet.cell(row = row, column = 1).value

        ip_list[ip] = {"index":row,"old_mac":old_mac}

    # print("ip_list: ",len(ip_list),"sheet.max_row: ",sheet.max_row-1)


    for i,j in ip_list.items():
        threading.Thread(target=run,args=(i,ip_list[i]["index"],ip_list[i]["old_mac"],)).start()
        while True:
            if len(threading.enumerate())>threa_num: #进程数
                time.sleep(5)
            else:
                break
    else:
        while True:
            if len(threading.enumerate())>=2: #进程数
                time.sleep(2)
            else:
                for i in change_list:
                    sheet1.cell(row = max_column1, column = 1).value = i["old_ip"]
                    sheet1.cell(row = max_column1, column = 2).value = i["new_ip"]
                    sheet1.cell(row = max_column1, column = 3).value = i["old_mac"]
                    sheet1.cell(row = max_column1, column = 4).value = i["new_mac"]
                    sheet1.cell(row = max_column1, column = 5).value = i["change_date"]
                    max_column1+=1
                    #修改原来的mac
                    sheet.cell(row = i["old_index"], column = 2).value = i["new_mac"]
                break
    wb.save(file)
    print("保存完成".center(30,"-"))

 需要自己建个定时任务来循环执行

 

 

posted @ 2020-08-01 16:37  chen~先生  阅读(734)  评论(0编辑  收藏  举报