学校图书馆有一本电子书,可以供学生阅读,但是怎么防止学生将其带出图书馆呢?我把它连上馆内的一台电脑的WiFi热点,间隔一段时间就从电脑ping这台电子书,如果ping不通,说明电子书脱离了WiFi信号范围,电脑就会响起报警声。
代码思路如下,先通过Windows上的arp命令,用设备的MAC地址获取其IP,再用ping命令检测设备是否在线,如果不在,就输出现在的时间、丢失设备IP和MAC地址,保存日志到文件,并播放报警声。
我尝试过给电子书贴RFID标签,但是RFID会受到电子书干扰,在通过门禁时无法像普通书籍一样报警。
如果各位还有什么好方法,欢迎评论!
import datetime
import sys
import time
import sched
import subprocess
from io import StringIO
try:
import playsound
except ImportError:
import os
os.system("pip install playsound")
import playsound
MY_DEVICE = ["48-e7-da-13-9e-b3"] # MAC addresses of my devices
device_ip = [""] * len(MY_DEVICE)
DETECT_DELAY = 5 # seconds
SOUND_PATH = "my_alert.mp3" # alert sound path
def detector():
lost = []
for i in range(len(device_ip)):
if device_ip[i] != "":
if subprocess.run("ping -n 2 -w 2500 " + device_ip[i], capture_output=True).returncode != 0:
lost.append(i)
if len(lost) > 0:
buffer = StringIO()
sys.stdout = buffer
now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print()
print(now_time)
print("Device lost:")
for dev_id in lost:
print(device_ip[dev_id], "", MY_DEVICE[dev_id])
output = buffer.getvalue()
sys.stdout = sys.__stdout__
print(output)
with open("./log.txt", "a") as file:
file.write(output)
while True:
playsound.playsound(SOUND_PATH)
else:
print("ok.")
loop_detect()
def loop_detect():
s = sched.scheduler(time.time, time.sleep)
s.enter(DETECT_DELAY, 6, detector, ())
s.run()
#get ip from its MAC address
def get_ip():
for line in subprocess.check_output("arp -a", shell=True).decode("gbk").splitlines():
for index in range(len(MY_DEVICE)):
if MY_DEVICE[index] in line:
ip = line[0:line.index(MY_DEVICE[index])].strip()
device_ip[index] = ip
for index in range(len(device_ip)):
if device_ip[index] == "":
print("Device not found in arp: ", MY_DEVICE[index])
else:
print("Device found in arp: ", device_ip[index], "", MY_DEVICE[index])
if __name__ == "__main__":
get_ip()
all_offline = True
for ip in device_ip:
if ip != "":
all_offline = False
break
if not all_offline:
print("Start detecting...")
loop_detect()
else:
print("All offline")
标签:index,防盗,Python,ip,WiFi,device,print,import,MY
From: https://www.cnblogs.com/mariocanfly/p/18068035