AppleScript – How to Toggle Network Services with a Script

applescriptNetwork

Currently I can do this only on a per connection basis using this script:

property status : "none"
property val : "none"

on get_status()
    set status to do shell script "sudo networksetup -getnetworkserviceenabled Ethernet" as string
end get_status

get_status()

if status is "Enabled" then
    set val to "off"
else
    set val to "on"
end if

do shell script "sudo networksetup -setnetworkserviceenabled Ethernet " & val

get_status()
display dialog "Status: " & status with title "Network Toggle" buttons {"OK"} default button 1

But recently I am getting network from different sources and I would like to have a script with toggles availability for all active connections (either all on or all off).

Any idea on how I could pull this off?

Best Answer

Use the -listallnetworkservices option to get all services.

tail -n +2 to delete the first line which contains "An asterisk (*) denotes that a network service is disabled."

sed 's/^*//' to delete the asterix character at beginning of each line

while read thisName to loop


The script:

if get_status() is "Enabled" then
    set val to "off"
else
    set val to "on"
end if
do shell script "networksetup -listallnetworkservices | tail -n +2 | sed 's/^*//' | while read thisName; do networksetup -setnetworkserviceenabled  \"$thisName\" " & val & "; done" with administrator privileges
display dialog "Status: " & (get_status()) with title "Network Toggle" buttons {"OK"} default button 1

on get_status()
    set status to do shell script "networksetup -getnetworkserviceenabled Ethernet"
end get_status

sudo in a do shell script command doesn't work on my system, I use administrator privileges.