Python 检测到新的 wifi 连接

Python detect new connection to wifi

我在 YouTube 上看到了一个教程(我不能 link 因为我找不到了), 所以代码应该检测连接到我的设备 Internet/Router,我不太了解他(制作教程的人)代码的工作原理

我的控制台也出现了这个错误:

File "c:/Users/j/Desktop/Connection-Detection.py", line 6, in IP_NETWORK = config('IP_NETWORK') File "C:\Users\j\AppData\Local\Programs\Python\Python38-32\lib\site-packages\decouple.py", line 199, in call return self.config(*args, **kwargs) File "C:\Users\j\AppData\Local\Programs\Python\Python38-32\lib\site-packages\decouple.py", line 83, in call return self.get(*args, **kwargs) File "C:\Users\j\AppData\Local\Programs\Python\Python38-32\lib\site-packages\decouple.py", line 68, in get raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option)) decouple.UndefinedValueError: IP_NETWORK not found. Declare it as envvar or define a default value. PS C:\Users\j\Desktop\python\login>

那是“Detection.py”

import sys
import subprocess
import os
from decouple import config

IP_NETWORK = config('IP_NETWORK')
IP_DEVICE = config('IP_DEVICE')

proc = subprocess.Popen(['ping', IP_NETWORK],stdout=subprocess.PIPE)

while True:
    line = proc.stdout.readline
    if not line:
        break
    connected_ip = line.decode('utf-8').split()[3]

    if connected_ip == IP_DEVICE:
        subprocess.Popen(['say', 'Someone connected to network'])



  

您需要在与 Detection.py 文件相同的目录中定义一个环境变量。

步骤

  1. 安装python-decouple - pip install python-decouple.
  2. 创建一个名为 .env
  3. 的文件
  4. 打开 .env 文件并将以下内容粘贴到其中。
IP_NETWORK=YOUR_IP_NETWORK
IP_DEVICE=YOUR_IP_DEVICE

YOUR_IP_NETWORKYOUR_IP_DEVICE 替换为您的 IP_NETWORK and IP_DEVICE