linux wifi自动连接脚本
1、新建 /etc/init.d/S88autowifi 内容如下:
#!/bin/sh
#
# Start the wifi....
#
# Debian ifupdown needs the /run/wifi lock directory
mkdir -p /run/wifi
#自定义变量
interface_dev="wlan0"
wifi_name="xxxxx"
wifi_password="xxxxx"
#加载WIFI驱动
cd /lib/modules/5.10.172/
insmod rtl8188fu.ko
cd ~
#执行wpa_cli前先调用wpa_supplicant不然不成功,不知道为何(wlan0不能替换为变量)
wpa_supplicant -i wlan0 -c/etc/wpa_supplicant.conf & iwconfig wlan0
#连接WIFI
func_connect_wifi()
{
echo "WIFI设备:$interface_dev"
#1、查询interface_dev网卡是否存在
# verifi_dev=`ifconfig|grep -ci "$interface_dev"`
# if [[ $verifi_dev == 0 ]];then
# echo "该设备不存在"
# exit -1
# fi
#1、查询interface_dev网卡是否存在
for i in {1..5}
do
verifi_dev=`ifconfig|grep -ci "$interface_dev"`
if [[ $verifi_dev == 0 ]];then
verifi_dev=`ifconfig|grep -ci "$interface_dev"`
echo "设备不存在"
sleep 2
else
echo "设备存在"
break
fi
done
#2、创建新链接
wifi_id=`wpa_cli -i $interface_dev add_network`
echo "准备建立新连接 wifi_id = $wifi_id"
#3、查找指定热点是否存在
result=$(wpa_cli -i $interface_dev set_network $wifi_id ssid \"$wifi_name\")
echo "result = $result"
if [[ $result != "OK" ]];then
echo "WIFI热点查找失败"
wpa_cli -i $interface_dev remove_network $wifi_id
exit -1
fi
#4、验证密码是否正确
result2=$(wpa_cli -i $interface_dev set_network $wifi_id psk \"$wifi_password\")
if [[ $result2 != "OK" ]];then
echo "WIFI密码错误连接失败"
wpa_cli -i $interface_dev remove_network $wifi_id
exit -1
fi
#5、连接WIFI
result3=$(wpa_cli -i $interface_dev enable_network $wifi_id)
echo "result = $result"
if [[ $result3 != "OK" ]];then
echo "连接失败"
wpa_cli -i $interface_dev remove_network $wifi_id
exit -1
fi
result4=$(wpa_cli -i $interface_dev select_network $wifi_id)
echo "result = $result4"
if [[ $result3 != "OK" ]];then
echo "WiFi切换失败"
exit -1
fi
#6、获取IP地址
echo "WiFi已切换开始自动分配IP"
resule5=$(udhcpc -b -i $interface_dev -q)
echo "连接完成"
exit 0
}
#断开WIFI
func_dele_wifi()
{
echo "WIFI关闭设备:$interface_dev"
#1、查询interface_dev网卡是否存在
verifi_dev=`ifconfig|grep -ci "$interface_dev"`
if [[ $verifi_dev == 0 ]];then
echo "该设备不存在"
exit -1
fi
#关闭interface_dev网卡
#wpa_cli -i $interface_dev list_network
wpa_cli -i $interface_dev remove_network $interface_dev
exit 0
}
case "$1" in
start)
printf "Starting wifi: "
func_connect_wifi
[ $? = 0 ] && echo "OK" || echo "FAIL"
;;
stop)
printf "Stopping wifi: "
func_dele_wifi
[ $? = 0 ] && echo "OK" || echo "FAIL"
;;
restart|reload)
"$0" stop
"$0" start
;;
*)
echo "Usage: $0 {start|stop|restart}"
exit 1
esac
exit $?