Run a script to log in to WiFi upon connect

wifi

My school network have a captive portal. Using Google Chrome's "copy as cURL" seems to log me in using curl, but I want to automate this process so it happens as soon as the mac connects to Wi-Fi. How would I achieve that?
The curl command is as follows:

curl 'http://1.1.1.3/ac_portal/login.php' -H 'Connection: keep-alive' -H 'Accept: */*' -H 'Origin: http://1.1.1.3' -H 'X-Requested-With: XMLHttpRequest' -H 'User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Mobile Safari/537.36' -H 'DNT: 1' -H 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8' -H 'Referer: http://1.1.1.3/ac_portal/20171018144956/pc.html?template=20171018144956&tabs=pwd&vlanid=0&url=http://www.gstatic.com/generate_204' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: zh' -H 'Cookie: ac_login_info=passwork; Sessionid=3566675246-1' --data 'opr=pwdLogin&userName=student&pwd=password&rememberPwd=1' --compressed --insecure

The network name is SCLSCHOOL_G, SCLSCHOOL_F, and SCLSCHOOL_H.

Best Answer

There’s nothing that allows you to kick off a script when you attach to a particular network, so you’ll have to use two tools

  • launchctl You’ll have to start the job based on network availability. Unfortunately, this only checks to see if you’re connected to any network, not a specific one.
  • networksetup that gets the current SSID you’re attached to. The command you will need is

    networksetup -listpreferredwirelessnetworks en1 | grep ${SSID} | cut -f2
    

Then in a bash script, compare the output of that command and if it matches the SSID you want, run the curl command.