2026/2/20

setup pi as a wifi ap

新的 pi os lite 已經不用 wpa_supplicant,改用 nmcli 了。
#!/bin/bash

# Configuration Variables
SSID="pi4app"
PASSWORD="pi4password"
AP_IP="192.168.4.1/24"
CON_NAME="Hotspot"
WLAN_IF="wlan0"

# 1. Check for root privileges
if [ "$EUID" -ne 0 ]; then
  echo "Please run as root (use sudo)"
  exit 1
fi

# 2. Check if nmcli is installed
if ! command -v nmcli &> /dev/null; then
    echo "Error: nmcli is not installed. This script requires NetworkManager."
    exit 1
fi

echo "--- Configuring Wi-Fi Access Point: $SSID ---"

# 3. Remove existing connection with the same name if it exists
nmcli connection delete "$CON_NAME" 2>/dev/null

# 4. Create the Hotspot connection
# - type wifi: Specifies a Wi-Fi connection
# - mode ap: Sets it to Access Point mode
# - band a: Sets it to 5GHz (use 'bg' for 2.4GHz)
# - ipv4.method shared: Enables internet sharing/NAT
# - ipv4.addresses: Sets a custom subnet to avoid conflicts with eth0
nmcli connection add type wifi ifname "$WLAN_IF" con-name "$CON_NAME" autoconnect yes ssid "$SSID" \
    802-11-wireless.mode ap \
    802-11-wireless.band a \
    ipv4.method shared \
    ipv4.addresses "$AP_IP" \
    wifi-sec.key-mgmt wpa-psk \
    wifi-sec.psk "$PASSWORD"

# 5. Explicitly ensure autoconnect is set to yes
nmcli connection modify "$CON_NAME" connection.autoconnect yes

echo "--- Activating $CON_NAME ---"

# 6. Bring the connection up
nmcli connection up "$CON_NAME"

echo "--- Setup Complete ---"
echo "Autoconnect status: $(nmcli -f connection.autoconnect connection show "$CON_NAME" | grep autoconnect)"
nmcli device status
ip addr show "$WLAN_IF"

沒有留言:

張貼留言