Files
archery/wpa_supplicant_conf.py
2026-05-13 16:38:24 +08:00

54 lines
1.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
生成 wpa_supplicant STA 配置(不经过 shell / wpa_passphrase避免中文 SSID 在 /bin/sh 传参时被破坏。
与 wpa_passphrase 一致PMK = PBKDF2-SHA1(password_utf8, ssid_utf8, 4096, 32)
ssid 行使用 UTF-8 字节的十六进制(无引号),与 wpa_supplicant 文档一致。
"""
from __future__ import annotations
import hashlib
_CTRL_HEADER = (
"ctrl_interface=/var/run/wpa_supplicant\n"
"update_config=1\n\n"
)
def _ssid_utf8_bytes(ssid: str) -> bytes:
b = (ssid or "").encode("utf-8")
if not b:
raise ValueError("SSID 为空")
if len(b) > 32:
raise ValueError("SSID UTF-8 超过 32 字节")
return b
def build_sta_conf_psk(ssid: str, password: str) -> str:
"""WPA2-PSK STA完整 wpa_supplicant.conf 文本。"""
ssid_b = _ssid_utf8_bytes(ssid)
pw = (password or "").encode("utf-8")
if len(pw) < 8 or len(pw) > 63:
raise ValueError("WPA2-PSK 密码长度应为 863 字节UTF-8")
pmk = hashlib.pbkdf2_hmac("sha1", pw, ssid_b, 4096, 32)
net = (
"network={\n"
f"\tssid={ssid_b.hex()}\n"
f"\tpsk={pmk.hex()}\n"
"}\n"
)
return _CTRL_HEADER + net
def build_sta_conf_open(ssid: str) -> str:
"""开放网络 STA完整 wpa_supplicant.conf 文本。"""
ssid_b = _ssid_utf8_bytes(ssid)
net = (
"network={\n"
f"\tssid={ssid_b.hex()}\n"
"\tkey_mgmt=NONE\n"
"}\n"
)
return _CTRL_HEADER + net