Albert Sikkema||2023-08-27

Category: tech

AppleScriptmacOSautomationWiFiEthernet
Toggle wifi when ethernet is plugged in

Toggle wifi when ethernet is plugged in

To automate the process of turning off WiFi when an Ethernet adapter is connected and turning it back on when the adapter is disconnected, you can use AppleScript in combination with launchd.

Here's a step-by-step guide:

1. Create an AppleScript to Check Ethernet Status and Toggle WiFi

  1. Open the "Script Editor" app on your Mac.
  2. Enter the following AppleScript:
do shell script "/usr/sbin/networksetup -listallhardwareports"

if result contains "USB Ethernet" then
    do shell script "/usr/sbin/networksetup -setairportpower en0 off"
else
    do shell script "/usr/sbin/networksetup -setairportpower en0 on"
end if
  1. Save the script as toggleWiFi.scpt to a directory of your choice, say ~/Documents/Scripts/.

2. Create a Launch Agent

  1. Use a text editor (like TextEdit) and create a new XML file with the following content:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.user.togglewifi</string>
    <key>ProgramArguments</key>
    <array>
        <string>osascript</string>
        <string>/Users/YOUR_USERNAME/Documents/Scripts/toggleWiFi.scpt</string>
    </array>
    <key>WatchPaths</key>
    <array>
        <string>/Library/Preferences/SystemConfiguration</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>StandardErrorPath</key>
    <string>/tmp/com.user.togglewifi.err</string>
    <key>StandardOutPath</key>
    <string>/tmp/com.user.togglewifi.out</string>
</dict>
</plist>

Replace YOUR_USERNAME with your actual username.

  1. Save this file as com.user.togglewifi.plist in the directory ~/Library/LaunchAgents/.

3. Load the Launch Agent

In the Terminal, run:

launchctl load ~/Library/LaunchAgents/com.user.togglewifi.plist

This will load your launch agent and it will start monitoring for changes in network connectivity. When an Ethernet connection is detected, the WiFi will be turned off, and vice versa.

If you want to unload the script in the future, you can use:

launchctl unload ~/Library/LaunchAgents/com.user.togglewifi.plist

This method relies on changes to the SystemConfiguration folder to detect network changes, which may not be as precise as listening for a specific USB-C Ethernet adapter. However, for many use cases, this should suffice. If you need a more targeted solution, additional scripting or third-party software might be necessary.