Skip to content

Instantly share code, notes, and snippets.

@stevenharman
Created June 16, 2020 16:25
Show Gist options
  • Save stevenharman/1eae5c57781e2f1f5670c7194e7db589 to your computer and use it in GitHub Desktop.
Save stevenharman/1eae5c57781e2f1f5670c7194e7db589 to your computer and use it in GitHub Desktop.

Revisions

  1. stevenharman created this gist Jun 16, 2020.
    81 changes: 81 additions & 0 deletions restart-network-services
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,81 @@
    #! /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"