Created
June 16, 2020 16:25
-
-
Save stevenharman/1eae5c57781e2f1f5670c7194e7db589 to your computer and use it in GitHub Desktop.
Restart Active Network Services on your Mac. You know, for the VPN!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env bash | |
# shellcheck disable=SC2059 | |
set -euo pipefail | |
# Toggle all currently 'Active' network servcies (e.g., Wi-Fi, Ethernet | |
# connections, etc...) to "restart" them. We'll ignore any already 'Disabled' | |
# services, and toggle all of the others to 'Disabled' and then back to | |
# 'Enabled'. This has been found helpful when your VPN won't re-connect after | |
# undocking and re-docking your MacBook, for example. | |
RED='\033[0;31m' | |
GREEN='\033[0;32m' | |
YELLOW='\033[0;33m' | |
NO_COLOR='\033[0m' | |
CLEAR_LINE='\r\033[K' | |
IFS=$'\n' | |
get_service_status() { | |
service=$1 | |
command=(networksetup -getnetworkserviceenabled "$service") | |
"${command[@]}" | |
} | |
report_service_status() { | |
service=$1 | |
service=$(echo "$service" | tr -d '*') # strip deactive indicator | |
status=$(get_service_status "$service") | |
status_sign=❔ | |
status_color=${YELLOW} | |
case "$status" in | |
"Enabled") | |
status_sign=✅ | |
status_color="${GREEN}" | |
;; | |
"Disabled") | |
status_sign=⛔️ | |
status_color="${RED}" | |
;; | |
esac | |
printf "$status_sign $service is ${status_color}$status${NO_COLOR}\n" | |
} | |
set_service_status() { | |
service=$1 | |
status=${2:-on} #default to on | |
networksetup -setnetworkserviceenabled "$service" "$status" | |
} | |
printf "📶 Checking network connections:\n" | |
services=$(networksetup -listallnetworkservices | sed -E '/.*asterisk.*disabled.*/d') | |
restartable_services=$(echo "$services" | sed -E '/^\*.*/d') # ignore already disabled services | |
echo "$services" | while read -r service; do | |
report_service_status "$service" | |
done | |
printf "\n🔧 Disabling services...\n" | |
echo "$restartable_services" | while read -r service; do | |
set_service_status "$service" off | |
done | |
echo "$services" | while read -r service; do | |
report_service_status "$service" | |
done | |
printf "\n🔧 Enabling services...\n" | |
echo "$restartable_services" | while read -r service; do | |
set_service_status "$service" on | |
done | |
echo "$services" | while read -r service; do | |
report_service_status "$service" | |
done | |
printf "\n📶 Network connections restarted. It could take a few moments for them to acquire IPs.\n" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment