MacOS睡眠唤醒后自动连接校园网(sleepwatcher)

在大学里使用校园网需要到固定的页面去输入账号和密码才可以使用,每次唤醒电脑后都要很繁冗地去:
1. 打开浏览器;
2. 点一下收藏认证网址;
3. 点一下已经记住了无数遍的密码;
4. 再去登陆.
至此才可以愉快的网上冲浪

最近才想找某些工具去解决这个每天都要面临好几次的问题。搜了一圈,macOS的终端命令没有什么hook能提示我从睡眠中唤醒,那只能去借助第三方的工具了,最后选用了一个免费版的sleepwatcher,够用就好。

如果已经安装了homebrew就很简单去安装sleepwatcher。

安装sleepwatcher

> brew install sleepwatcher

设置软件服务自启动

> brew services start sleepwatcher

我们这里只要使用从睡眠中唤醒的功能,首先编写唤醒脚本:

> vi ~/.wakeup

连接网络的脚本是用python写的

import base64
import json
import requests
from sys import argv
from typing import List


class xxx_account:
    """ xxx account """

    xxx_login_url = 'http://xxx'
    xxx_domains = {'移动': 'CMCC', '电信': 'ChinaNet', '联通': 'Unicom'}

    def __init__(self, username: str, domain: str, password: str):
        self.username = username
        self.domain = self.xxx_domains[domain] if domain in self.xxx_domains else domain
        self.password = self.pw_encode(password)

    @staticmethod
    def pw_encode(password: str) -> bytes:
        """encode password"""
        return base64.b64encode(password.encode())

    @staticmethod
    def xxx_login(login_url, username, domain, password_b64: bytes) -> requests.Session:
        """xxx login """
        login_data = {
            'username': username,
            'domain': domain,
            'password': password_b64,
            'enablemacauth': '0'
        }
        headers_base = {
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Connection': 'keep-alive',
            'Host': 'xxx',
            'User-Agent': \
                'Mozilla/5.0 (X11; Linux x86_64) ' + \
                'AppleWebKit/537.36 (KHTML, like Gecko) ' + \
                'Chrome/63.0.3239.108 Safari/537.36 '
            # X-Requested-With:XMLHttpRequest
        }
        return requests.session().post(login_url, headers=headers_base, data=login_data)

    @staticmethod
    def xxx_login_response_disp(login_response: requests.Response):
        """ print response of `xxx_login()` beautifully"""
        # contdict = eval(login_response.text.replace('null', '""'))
        # for i in contdict:
        #     data = eval(f'u"{contdict[i]}" ')
        #     print(f'  {i:16} : {data}')
        contdict = json.loads(login_response.text)
        for i, v in contdict.items():
            print(f'\t{i:16} : {v}')


    def login(self) -> bool:
        print(f'Trying to login xxx as {self.domain}:{self.username}')
        print('please wait...')
        self.xxx_login_response_disp(
            self.xxx_login(
                ixxx_account.xxx_login_url,
                self.username,
                self.domain,
                self.password
            )
        )
        return True # always True...

    def logout(self) -> bool:
        # not implemented yet, sorry
        return False


# def WALN_join(SSID: str) -> bool:
#     """join WLAN.
#     incomleted for linux, be cautious"""
#     from os.sys import platform
#     from os import system
#     if platform == 'linux':
#         wpa_interface = '' # !!!
#         wpa_conffile = '' # !!!
#         system(f'wpa_supplicant -B -c{wpa_conffile} -i{wpa_interface}') == 0
#     elif platform == 'win32':
#         return system(f'netsh wlan connect name="{SSID}"') == 0
#     else:
#         return False



def main():
    account_default = []
    account_default.append(xxx_account('xxxxxx', 'Unicom', 'xxxx'))
    account_default.append(xxx_account('xxxxxx', '移动', 'xxxx'))

    try:
        # WALN_join() # assume that has connected to Wi-Fi

        # the first arg desides which account to use, default account[0]
        account_default[0 if len(argv) <= 1 else int(argv[1])].login()
    except Exception as e:
        # Exceptions are raised sometimes, don't know how to deal with it
        print(e)


if __name__ == '__main__':
    main()

把里面的xxx改成自己需要的就可以了。
将python脚本(Wi-Fi_login.py)保存在某个位置,这里我是保存在桌面上。

然后在刚刚的.wakeup文件中写入:

#!/bin/bash
networksetup -setairportpower en0 on  # 打开Wi-Fi
networksetup -setairportnetwork en0 Wi-Fi_name  # 连接到指定的Wi-Fi
sleep 5 # 等待5秒
python desktop/Wi-Fi_login.py  #执行python脚本

如果没有sleep 5的话可能会导致电脑还没有连接上Wi-Fi,就已经执行验证脚本,等待的时间可以自己测试来更改。

赋予文件权限

sudo chmod 777 ~/.wakeup

最后就可以运行程序了

/usr/local/sbin/sleepwatcher --verbose --wakeup ~/.wakeup

这样整个的流程就结束了,下次再掀开电脑,只要等待几秒钟,Wi-Fi就可以自动连接上了,懒人必备。

你可能感兴趣的:(杂论)