开发板开机自动连wifi

点击查看代码
#!/bin/bash

# Function to scan surrounding WiFi networks
scan_wifi() {
    iwlist wlan0 scan > /tmp/wifi_scan.txt
}

# Function to connect to a WiFi network
connect_to_wifi() {
    SSID=$1
    PASSWORD=$2
    echo "连接到 WiFi,SSID: $SSID"
    wpa_passphrase "$SSID" "$PASSWORD" > /userdata/cfg/wpa_supplicant.conf
    wpa_supplicant -B -i wlan0 -c /userdata/cfg/wpa_supplicant.conf
    dhclient wlan0
}

# Main function
main() {
    # Scan surrounding WiFi networks
    scan_wifi
    
    # Read the scan results and extract SSIDs
    SSIDS=($(grep "ESSID:" /tmp/wifi_scan.txt | awk -F'"' '{print $2}'))
    
    # Define WiFi SSIDs and passwords in a table
    declare -A WIFI_TABLE
    WIFI_TABLE["ChinaNet-Cd39"]="ylfczyjg"
    WIFI_TABLE["Redmi"]="12345679"
    WIFI_TABLE["Your_SSID_3"]="Your_Password_3"
    
    # Loop through the scanned SSIDs and try to connect to each one
    for SSID in "${SSIDS[@]}"; do
        PASSWORD=${WIFI_TABLE["$SSID"]}
        if [ -n "$PASSWORD" ]; then
            connect_to_wifi "$SSID" "$PASSWORD"
            # Check if connection successful
            if [[ $? -eq 0 ]]; then
                echo "连接成功!"
                exit 0  # Exit the script if connected successfully
            else
                echo "连接失败,尝试下一个网络..."
            fi
        fi
    done
    
    echo "没有找到匹配的网络。"
    exit 1
}

# Run the main function
main
目标平台:rk3566 buildroot 代码命名为"Swifi" 保存到/etc/init.d 注意:必须以大写'S'开头,/etc/init.d/下有文件rcS,会读取S开头的文件作为启动项,命名为"Swifi"是为了能让改脚本发挥作用.
posted @ 2024-02-26 13:52  760g  阅读(8)  评论(0编辑  收藏  举报