Actionable rules and patterns for automating and maintaining reliable, secure network configurations on macOS using built-in tools and shell scripting.
Your macOS network setup shouldn't require 20 clicks every time you switch environments. Whether you're bouncing between office VPN, home Wi-Fi, and coffee shop connections, these automation rules eliminate the tedious configuration dance that kills productivity.
You know the drill: new office, new VPN settings. Working from home? Different DNS servers. Coffee shop coding session? Manual proxy adjustments. Each environment change means:
Developers managing multiple environments waste 2-3 hours weekly on network configuration tasks that should take seconds.
These Cursor Rules transform macOS network management from manual clicking into automated, version-controlled infrastructure. Using built-in networksetup, scutil, and shell scripting, you'll create self-documenting network configurations that adapt to your workflow instead of interrupting it.
What You Get:
# 15 manual steps to switch from home to office
# 1. Open System Settings
# 2. Click Network
# 3. Disable Wi-Fi
# 4. Configure VPN
# 5. Set corporate DNS
# 6. Enable proxy
# 7. Test connection
# 8. Troubleshoot when it fails
# 9. Repeat until working
# Single command, 30 seconds, zero errors
./network-config.sh --location office --apply
Time Savings: 10+ minutes per environment switch → 30 seconds
Error Reduction: Manual typos eliminated → Zero-config failures
Workflow Impact: Context switching disruption → Seamless environment adaptation
Instead of manually reconfiguring network settings for each location:
#!/usr/bin/env zsh
set -euo pipefail
switch_to_office() {
echo "[INFO] Switching to office environment..."
# Create and switch to office location
networksetup -createlocation "Office" populate 2>/dev/null || true
networksetup -switchtolocation "Office"
# Configure corporate VPN
networksetup -connectpppoeservice "Corporate VPN"
# Set corporate DNS
networksetup -setdnsservers "Wi-Fi" 10.0.1.1 10.0.1.2
# Enable corporate proxy
networksetup -setwebproxy "Wi-Fi" proxy.corp.com 8080 on
# Test connectivity
if ping -c3 internal.corp.com >/dev/null 2>&1; then
echo "[INFO] Office environment ready"
else
echo "[ERROR] Office connection failed" >&2
rollback_network_changes
fi
}
Stop manually hunting for the best channels and dealing with interference:
optimize_wifi() {
local interface="Wi-Fi"
local current_channel
echo "[INFO] Scanning for optimal Wi-Fi channel..."
# Get current channel and signal strength
current_channel=$(airport -I | grep -E '^\s*channel' | awk '{print $2}')
# Scan available networks and interference
airport -s | grep -E "(Ch\s+[0-9]+|RSSI)" > /tmp/wifi_scan
# Auto-select optimal 5GHz channel
if [[ $(airport -I | grep -c "CC:.*802.11ac\|802.11ax") -gt 0 ]]; then
networksetup -setairportnetwork "$interface" "$SSID" "$PASSWORD"
echo "[INFO] Connected to 5GHz band for optimal performance"
fi
}
Eliminate VPN connection failures and security gaps:
setup_secure_vpn() {
local vpn_name="$1"
local server="$2"
# Validate VPN prerequisites
if ! networksetup -listallnetworkservices | grep -q "VPN"; then
echo "[ERROR] VPN service not configured" >&2
return 1
fi
# Import VPN configuration securely
scutil --nc import "$vpn_name" /path/to/config.mobileconfig
# Store credentials in Keychain (never plaintext)
security add-generic-password -a "$USER" -s "$vpn_name" -w "$VPN_PASSWORD"
# Test VPN connection with automatic retry
retry_vpn_connection "$vpn_name"
}
# Create project structure
mkdir ~/network-automation
cd ~/network-automation
# Initialize with basic script template
cat > network-config.sh << 'EOF'
#!/usr/bin/env zsh
set -euo pipefail
# Configuration constants
readonly SCRIPT_DIR="$(dirname "$0")"
readonly CONFIG_DIR="$HOME/.network-configs"
readonly BACKUP_DIR="$CONFIG_DIR/backups"
# Create necessary directories
mkdir -p "$CONFIG_DIR" "$BACKUP_DIR"
EOF
chmod +x network-config.sh
# Add location management functions
create_network_location() {
local location_name="$1"
echo "[INFO] Creating network location: $location_name"
# Backup current settings
backup_network_config
# Create new location
if ! networksetup -createlocation "$location_name" populate; then
echo "[ERROR] Failed to create location $location_name" >&2
return 1
fi
networksetup -switchtolocation "$location_name"
echo "[INFO] Switched to $location_name"
}
test_network_connectivity() {
local test_urls=("1.1.1.1" "8.8.8.8" "google.com")
for url in "${test_urls[@]}"; do
if ! ping -c3 "$url" >/dev/null 2>&1; then
echo "[ERROR] Cannot reach $url" >&2
return 1
fi
done
echo "[INFO] Network connectivity verified"
return 0
}
rollback_on_failure() {
echo "[WARN] Network configuration failed, rolling back..."
restore_network_backup
networksetup -switchtolocation "Automatic"
}
# Home configuration
configure_home_network() {
create_network_location "Home"
# Optimized home Wi-Fi settings
networksetup -setairportnetwork "Wi-Fi" "$HOME_SSID" "$HOME_PASSWORD"
networksetup -setdnsservers "Wi-Fi" 1.1.1.1 1.0.0.1
# Disable corporate proxy
networksetup -setwebproxystate "Wi-Fi" off
test_network_connectivity || rollback_on_failure
}
# Office configuration
configure_office_network() {
create_network_location "Office"
# Corporate network settings
networksetup -setdnsservers "Wi-Fi" 10.0.1.1 10.0.1.2
networksetup -setwebproxy "Wi-Fi" proxy.company.com 8080 on
# Connect to VPN
networksetup -connectpppoeservice "Company VPN"
test_network_connectivity || rollback_on_failure
}
Stop clicking through System Settings every time you change locations. Your network configuration should adapt to your workflow, not control it. These automation rules turn macOS network management into the reliable, hands-off infrastructure it should be.
The difference between manually configuring networks and automated network management isn't just time saved—it's the difference between treating network setup as a daily frustration versus invisible infrastructure that just works.
You are an expert in macOS network configuration, shell scripting (zsh/bash), Wi-Fi optimization, DHCP, VPN, and diagnostic tooling.
Key Principles
- Automate repetitive network tasks with idempotent shell scripts.
- Prefer built-in macOS tools (`networksetup`, `scutil`, `ifconfig`, `wifi_diag`) before third-party utilities.
- Keep scripts safe for interactive and headless runs; always support `--dry-run`.
- Fail fast: verify prerequisites (admin rights, interface existence) at the top and abort on error.
- Preserve existing user settings by exporting a backup (`/usr/libexec/PlistBuddy -c print`) before modifying them.
- Use human-readable, self-documenting names for network services and locations (e.g., "Home-WiFi", "Office-Ethernet-VPN").
- Always prioritise security (WPA3 > WPA2, never WEP/Open) and firmware currency.
Shell (zsh/bash)
- Begin scripts with `#!/usr/bin/env zsh` and `set -euo pipefail`.
- Quote all variable expansions (`"${var}"`) to avoid word-splitting.
- Use lowercase snake_case for variable names; UPPER_SNAKE for constants.
- Wrap hazardous commands in functions (e.g., `change_channel() { … }`).
- Provide usage help via a `--help` flag using a dedicated `usage()` function.
- Log actions with `echo "[INFO] …"` and warnings/errors with `>&2`.
Error Handling and Validation
- Always check command exit status: `if ! networksetup …; then …; fi`.
- Validate hardware port exists: `if ! networksetup -listallhardwareports | grep -q "Wi-Fi"; then error "Wi-Fi interface not found"; fi`.
- Test reachability after changes using `ping -c3 1.1.1.1` and fail rollback on loss.
- Renew DHCP leases immediately after IP-related changes: `ipconfig set $iface DHCP`.
- Provide clear user remediation in error messages (e.g., "Try toggling Wi-Fi off/on or reboot")
networksetup (Framework-Specific Rules)
- Prefer service names over interface IDs to remain stable across macOS updates.
- Create logical Locations:
`networksetup -createlocation "Office" populate`
`networksetup -switchtolocation "Office"`
- Channel optimisation:
- 2.4 GHz: `networksetup -setairportnetwork Wi-Fi "SSID" "pass" 1,6,11` (use 20 MHz width only).
- 5/6 GHz: allow auto width; verify country code supports DFS channels before enabling 149+.
- DNS:
`networksetup -setdnsservers Wi-Fi 1.1.1.1 1.0.0.1`; always append `Empty` to restore DHCP.
- VPN (IKEv2/L2TP):
- Use `scutil --nc import` for mobileconfig or `networksetup -importvpnsettings` on macOS 13+.
- Store shared secrets in Keychain, never plain text.
- Proxy: enable per-location when on corporate networks: `networksetup -setwebproxy Wi-Fi proxy.corp 8080 on`.
Additional Sections
Security
- Enforce WPA3 or WPA2 AES; audit with `/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I`.
- Disable automatic joining of rogue open networks: `networksetup -setairportpower Wi-Fi off && …` then re-enable.
- Keep macOS & router firmware updated; recommend `softwareupdate --install --all` weekly.
Performance
- Prefer 5 GHz/6 GHz bands: use `airport -s` to list scan results and auto-associate strongest 5 GHz network.
- Minimise interference: periodically run `sudo /System/Library/.../airport -z; airport -s` and adjust router channel.
- Measure throughput with `iperf3`; target >80% of link speed.
Testing & Diagnostics
- Use Wireless Diagnostics (⌥-click Wi-Fi icon > Open Diagnostics) for logs and sample.
- CLI quick health: `airport -I | egrep "agrCtlRSSI|channel"`.
- Automate regression tests after script changes: check (1) Internet reachability, (2) DNS resolution, (3) VPN connect.
Backup & Restore
- Backup all network preferences:
`sudo defaults export /Library/Preferences/SystemConfiguration com.apple.network > backup.plist`
- Restore with:
`sudo defaults import /Library/Preferences/SystemConfiguration < backup.plist && sudo reboot`
Common Pitfalls
- Editing `SystemConfiguration` plists by hand; always use official CLIs.
- Forgetting to renew DHCP after static IP changes; leads to conflicts.
- Mixing IPv4 manual and IPv6 automatic causing routing loops; be explicit for both.
Reference Commands (cheat-sheet)
```
# List services
networksetup -listallnetworkservices
# Toggle Wi-Fi
networksetup -setairportpower Wi-Fi off ; sleep 2 ; networksetup -setairportpower Wi-Fi on
# Set manual IP
networksetup -setmanual Wi-Fi 192.168.1.10 255.255.255.0 192.168.1.1
# Enable DHCP again
networksetup -setdhcp Wi-Fi
# Show current location
scselect
```