我有以下脚本,可以从当前 WiFi 网络断开连接并根据以下内容重新连接wpa_supplicant.conf
:
#!/bin/bash
if iwgetid; then
sudo wpa_cli terminate
sudo ip addr flush wlan0
sudo ip link set dev wlan0 down
sudo rm -r /var/run/wpa_supplicant > /dev/null
fi
sudo wpa_supplicant -B -i wlan0 -c /etc/wpa_supplicant/wpa_supplicant.conf > /dev/null 2>&1
sudo service ntp restart
sudo ip link set dev wlan0 down
sudo ip link set dev wlan0 up
sudo dhclient wlan0
问题是,如果凭据wpa_supplicant
不正确(这些凭据基于我的应用程序中的用户输入,因此很有可能),dhclient
则会挂起相当长一段时间,尝试连接到 DHCP 服务器并分配 IP 地址,然后最终失败。
有没有办法在调用之前测试凭据是否正确dhclient
?
答案1
这是一个示例./script
,包括wpa_passphrase
设置 TheSSID
和 the 的命令password
:
#!/bin/bash
if iwgetid; then
wpa_cli terminate
ip addr flush wlan0
ip link set dev wlan0 down
rm -r /var/run/wpa_supplicant > /dev/null
ip link set dev wlan0 up
fi
wpa_supplicant -B -i wlan0 -c<(wpa_passphrase "$1" "$2") > /dev/null 2>&1
dhclient wlan0
service ntp restart
exit
用法:
sudo ./script "My SSID" "My-Password"
更新
如果wpa_supplicant
使用给定的身份验证成功ssid
,pass
您将获得WPA: Key negotiation completed
日志文件。
-f
添加到wpa_supplicant
命令中以提供文件的选项log
。
grep
您可以在执行命令之前检查退出状态dhclient
。
#!/bin/bash
if iwgetid; then
wpa_cli terminate
ip addr flush wlan0
ip link set dev wlan0 down
rm -r /var/run/wpa_supplicant > /dev/null
ip link set dev wlan0 up
fi
# A minimal wpa_supplicant.conf configuration file.
echo -e "\nctrl_interface=/run/wpa_supplicant \nupdate_config=1\n" > /etc/wpa_supplicant/wpa_supplicant.conf
# A prompt for SSID and WPA passphrase. The -f option to get a log file.
# sleep command will be useful because the authentication will take a few
# second before executing grep.
echo "" > logfile
wpa_supplicant -B -i wlan0 -c<(wpa_passphrase "$1" "$2") -f logfile
sleep 10
grep -c "WPA: Key negotiation completed" logfile
if [ $? -eq 0 ]
then
echo "Key negotiation completed successfully"
timeout 15 dhclient wlan0
exit 0
else
echo "Authentication failed"
fi
exit 1
用法:
sudo ./script "My SSID" "My-Password"
答案2
我会将其分解为单独的函数,以便我在重新配置网络之前测试 wifi 连接。
#!/usr/bin/env bash
CONF="/etc/wpa_supplicant/wpa_supplicant.conf"
function connect_wifi() {
wpa_supplicant -B -i wlan0 -c $CONF >/dev/null 2>&1
}
function connect_tcpip() {
service ntp restart
ip link set dev wlan0 down
ip link set dev wlan0 up
dhclient wlan0
}
FUNC_CW=$(declare -f connect_wifi)
FUNC_CT=$(declare -f connect_tcpip)
if (sudo bash -c "$FUNC_CW; connect_wifi"); then
sudo bash -c "$FUNC_CT; connect_tcpip"
else
echo "Error Connecting to Wifi. Please check your credentials and try again."
fi