Auto run a shell script when connecting to a network? (wifi or utp)

applescriptautomationNetworkscriptwifi

Is there a way to make macOS run a custom script whenever it (re)connects to any WiFi or Ethernet network?

Basically, whenever my macbook connects to any network (wired or wireless) I would like to automatically run a shell script, e.g. I want ~/AutoRunOnConnect.sh to be executed. Is that possible somehow?

FYI I'm running macOS 10.15 (Catalina) with all the latest updates.

Best Answer

I use a program named EventScripts which among the events it monitors, there are Network Events, i.e., Internet became available, Internet became unavailable, External IP address changed and Wireless network changed. Update: In the latest release there is also a Wireless network reconnected event not shown on the linked webpage.

It uses AppleScript scripts to preform the action(s) you want to have happen when a given event is triggered.

You can execute a shell command/script using the AppleScript do shell script command.

Not sure if any of these can be adopted for your use, and it will probably require some additional coding, either in AppleScript or shell script to validate the conditions are met for wanting the main shell script to run. Just wanted to offer a possible solution.


It is a paid app, $4.99 USD, but does have a demo version you can download to test with before purchasing.


Note: Other then being a paid user of this app, I have no affiliation with its developer.