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

admin5年前网络管理83

说明:采用多线程监测局域网内主机的IP、MAC地址的异动变化并记录在Excel表格内 

 环境:python3.5    

pip3 install scapy    

pip3 install openpyxl 

 使用:python3 mac_change.py

# -*- 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,"-"))

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

image.png

image.png

相关文章

ubuntu系统开启root账户远程登录

123456789安装ssh-serversudo apt-get install openssh-serversudo nano /etc/ssh/...

ubuntu踢掉远程用户登录

12345#永久删除远程登录用户:    usermod –G peter 用户#仅仅想把远程登录用户踢掉:fuser -k /dev/pt...

mysql开启远程访问

mysql开启远程访问

123456789101112#1.在连接服务器后,操作mysql系统数据库mysql -u root -puse mysql;GRANT ALL PRIVILEGES ON *.* TO ...

ubuntu crontab设置定时任务

ubuntu 设置定时任务 crontab -l  #查看详情crontab -e #设置定时任务 *  *  *  *  *  command 分 ...

多线程监测局域网内主机的每晚关机情况并记录在Excel表格内

多线程监测局域网内主机的每晚关机情况并记录在Excel表格内

说明:采用多线程监测局域网内主机的每晚关机情况并记录在Excel表格内,主要通过命令行的ping命令实现。 环境:python3.5    pip3 install su...

ubuntu 16.04 搭建 pptp vpn

ubuntu 16.04 搭建 pptp vpn

1234567891011121314151617181920212223242526272829303132333435363738394041424344451.安装pptp以提供VPN服务sud...

发表评论    

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。
Music