Start/stop internet sharing from a script?

Is there a way to start/stop internet sharing from the command line or maybe an apple script?

The thing is that I move around my laptop between home and work. At one place I get wireless internet (and thus I have to disable internet sharing), and at the other I get internet from an ethernet cable and set up the computer to share the internet to other devices by creating a small wireless network.

But it's getting a bit tedious having to go into System Preferences and start/stop the internet sharing every time I switch locations, so I would like to have a quick command or script to launch and do the switch on demand.

Any hints or ideas?


Solution 1:

To start Internet Sharing from the CLI:

sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.InternetSharing.plist

To stop, change the load to unload.

Note that if you have the pref pane open when you run this you will not see the change take effect immediately (the UI won't update), but it does work.

Solution 2:

One way of doing this is by GUI scripting—System Preferences doesn't have any Applescript support by default.

tell application "System Preferences" to set current pane to pane "com.apple.preferences.sharing"
delay 1
tell application "System Events" to tell process "System Preferences"
    click checkbox 1 of row 8 of table 1 of scroll area 1 of group 1 of window "Sharing" -- change to row 10 if you are using anything before Snow Leopard
    delay 1
    if (exists sheet 1 of window "Sharing") then
        click button "Start" of sheet 1 of window "Sharing"
    end if
end tell
ignoring application responses
    tell application "System Preferences" to quit
end ignoring

Solution 3:

I had far better results (for an already configured sharing setup) on 10.11.6 with the simple variations...

sudo launchctl start com.apple.NetworkSharing

and

sudo launchctl stop com.apple.NetworkSharing

respectively.