1. 程式人生 > 實用技巧 >監測區域網內主機的IP、MAC地址的異動變化並記錄在Excel表格內

監測區域網內主機的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,"-"))

 需要自己建個定時任務來迴圈執行