写了几天 Python,顺手用 Python 把之前写的校园网认证脚本用 Python 优化重构了一遍。本来想部署到路由器上,结果路由器的 Python3 只能装到 USB 外置储存里(我放弃路由器挂硬盘做 Time Machine 了,因为 OPT 安装在硬盘中导致硬盘无法正常休眠,长期下来对硬盘损伤过大),所以最后继续用 shell 把之前的代码优化了一下。

顺便这里是我用 Python 写的登录脚本,用 PyInstaller 打包一下就可以得到 PC 端一键登录工具。
Sky1wu/Campus_Network_Login


login_response=$(curl -s 'http://172.16.251.172:8081/authentication/form' -X POST -H 'Authorization: Basic eGlhb2RlOnhpYW9kZTEyMw==' --data 'username='${username}'&password='${password})

首先发送登录请求,获取认证所需的 token,这里相比之前主要删除了部分不必要的参数,代码更加简洁。

temp=${login_response#*\":\"}
access_token=${temp%%\",\"*}

接下来从上面的返回值中获取截取 token,还是采用之前的字符串截取方案。其实如果装了 opt 环境,可以用里面内置的 jq,用下面的命令可以更方便地解析返回的 json。

access_token=$(echo $login_response | jq -r '.access_token')

之后从通过这个 URL 获取一下当前的认证状态,通过其返回值确认是否已认证(之前采用的方案是 ping baidu.com,如果网络不稳定没有 ping 通就会发送认证请求,可能会使本来已认证的网络断开)

status_response=$(curl -s 'http://172.16.251.172:8081/portal/wifi/status' -X POST -H 'Authorization: bearer '${access_token})

从返回的 json 里提取数字得到状态码。

code=`echo $status_response | tr -cd "[0-9]"`

同样的,如果有 jq 的话可以用下方的命令。

code=$(echo $status_response | jq -r '.code')

通过测试可得认证成功的返回 code 为 12001,最后就写一个判断,如果当前的状态 code 不为 12001 就发送认证请求完成认证。

online_code=12001

if [ $code -ne $online_code ]
then
    curl -s 'http://172.16.251.172:8081/portal/wifi/login' -X POST -H 'Authorization: bearer '${access_token}
else
    echo 'online'
fi
Last modification:November 1st, 2019 at 05:31 pm
If you think my article is useful to you, please feel free to appreciate