#!/bin/sh
#
# Start the wifi....
#
# Debian ifupdown needs the /run/wifi lock directory
mkdir -p /run/wifi
#自定义变量
interface_dev="wlan0"
wifi_name="xxxx"
wifi_password="xxxx"
#执行wpa_cli前先调用wpa_supplicant不然不成功,不知道为何
wpa_supplicant -i wlan0 -c/etc/wpa_supplicant.conf & iwconfig wlan0
func_connect_wifi()
{
echo "WIFI设备:$interface_dev"
#查询interface_dev网卡是否存在
verifi_dev=`ifconfig|grep -ci "$interface_dev"`
if [[ $verifi_dev == 0 ]];then
echo "该设备不存在"
exit -1
fi
wifi_id=`wpa_cli -i $interface_dev add_network`
echo "准备建立新连接 wifi_id = $wifi_id"
wpa_cli -i $interface_dev scan
echo "当前环境WiFi信息:"
wpa_cli -i $interface_dev scan_result
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 wlan0 remove_network $wifi_id
exit -1
fi
result2=$(wpa_cli -i $interface_dev set_network $wifi_id psk \"$wifi_password\")
if [[ $result2 != "OK" ]];then
echo "WIFI密码错误连接失败"
wpa_cli -i wlan0 remove_network $wifi_id
exit -1
fi
result3=$(wpa_cli -i $interface_dev enable_network $wifi_id)
echo "result = $result"
if [[ $result3 != "OK" ]];then
echo "连接失败"
wpa_cli -i wlan0 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
echo "WiFi已切换开始自动分配IP"
resule5=$(udhcpc -b -i $interface_dev -q)
echo "连接完成"
exit 0
}
func_dele_wifi()
{
echo "WIFI关闭设备:$interface_dev"
verifi_dev=`ifconfig|grep -ci "$interface_dev"`
if [[ $verifi_dev == 0 ]];then
echo "该设备不存在"
exit -1
fi
echo "当前WiFi列表"
wpa_cli -i $interface_dev list_network
echo "选择删除对象"
read wifi_id
wpa_cli -i $interface_dev remove_network $wifi_id
}
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 $?
标签:脚本,cli,wifi,dev,echo,interface,wpa,连接 From: https://www.cnblogs.com/linux-learn/p/18278109