How to start/stop Internet Sharing using AppleScript - applescript

I don't have a Wi-Fi router, so when at home I need to turn my laptop into a Wi-Fi source so that both myself and my partner can access the internet.
However during the days I work at a coffee shop and require the use of their Wi-Fi.
I'm running Snow Leopard and I find it stupidly cumbersome to constantly be turning off and on, first Internet Sharing and then my Wi-Fi.
Any ideas for a quick 'n' dirty AppleScript solution?

You can use launchctl to programmatically start or stop the Internet Sharing service.
The following AppleScript will start Internet Sharing:
do shell script "/bin/launchctl load -w /System/Library/LaunchDaemons/com.apple.InternetSharing.plist" with administrator privileges
The following AppleScript will stop Internet Sharing:
do shell script "/bin/launchctl unload -w /System/Library/LaunchDaemons/com.apple.InternetSharing.plist" with administrator privileges

I'm using this AppleScript from Automator so that I can easily use it as a service and give it a keyboard shortcut.
Toggle Internet Sharing:
register_growl()
try
if isRunning("InternetSharing") then
do shell script "launchctl unload -w /System/Library/LaunchDaemons/com.apple.InternetSharing.plist" with administrator privileges
if isRunning("InternetSharing") then
error "Internet Connection Sharing was Not Disabled"
else
my growlnote("Success", "Internet Connection Sharing Disabled")
end if
else
do shell script "launchctl load -w /System/Library/LaunchDaemons/com.apple.InternetSharing.plist" with administrator privileges
if isRunning("InternetSharing") then
my growlnote("Success", "Internet Connection Sharing Enabled")
else
error "Internet Connection Sharing was Not Enabled"
end if
end if
on error errMsg
my growlnote("Error", errMsg)
end try
on isRunning(processName)
try
return 0 < length of (do shell script "ps ax | grep -v grep | grep " & processName)
on error
return false
end try
end isRunning
on register_growl()
try
tell application "GrowlHelperApp"
set the notificationsList to {"Success", "Warning", "Error"}
register as application "Toggle Internet Connection Sharing" all notifications notificationsList default notifications notificationsList icon of application "Sharing"
end tell
end try
end register_growl
on growlnote(growltype, str)
try
tell application "GrowlHelperApp"
notify with name growltype title growltype description str application name "Toggle Internet Connection Sharing"
end tell
end try
end growlnote
I am cross-posting this on the Apple stack exchange because the question was asked in both places.

Not sure if you are still looking for a solution but... here is an apple script to enable or disable internet sharing
tell application "System Preferences"
activate
reveal (pane id "com.apple.preferences.sharing")
end tell
tell application "System Events"
tell process "System Preferences"
try
click checkbox of row 11 of table 1 of scroll area of group 1 of window "Sharing"
if checkbox of row 11 of table 1 of scroll area of group 1 of window "Sharing" is equal to 1 then
repeat until sheet of window 1 exists
delay 0.5
end repeat
end if
if (sheet of window 1 exists) then
click button "Start" of sheet of window 1
end if
tell application "System Preferences" to quit
activate (display dialog "Internet Sharing preferences sucessfully flipped")
on error
activate
display dialog "something went wrong in automation but you are probably in the right menu..."
return false
end try
end tell
end tell
I also will post this on the apple stack exchange post.

Here's what I came up with for Mojave to toggle Internet Sharing using (mostly) accessibility — unfortunately none of the solutions involving using launchctl and/or editing com.apple.nat.plist worked for me.
open location "x-apple.systempreferences:com.apple.preferences.sharing?Internet"
tell application "System Events"
tell process "System Preferences"
repeat until window "Sharing" exists
delay 0.1
end repeat
tell window "Sharing"
set _row to group 1's scroll area 1's table 1's first row whose selected is true
set _wasSharing to _row's checkbox's value as number
if _wasSharing is 1 then
click _row's checkbox
set _wasSharing to _row's checkbox's value as number
repeat until _wasSharing is 0
delay 0.1
end repeat
end if
if _wasSharing is 0 then
click _row's checkbox
repeat until sheet 1 exists
delay 0.1
end repeat
click sheet 1's button "Start"
end if
end tell
end tell
end tell
tell application "System Preferences" to quit

Related

applescript access switch control through system preferences

My end goal is to click the "Enable Switch Control" checkbox, which can be found under Accessibility-> Switch Control in System Preferences. I have had some trouble getting the applescript to work and would like to find out what is causing the issue.
My current code:
if running of application "System Preferences" then
quit application "System Preferences"
delay 1
end if
tell application "System Preferences"
reveal anchor "Switch" of pane id "com.apple.preference.universalaccess"
activate
end tell
I got the anchor Switch by using:
tell application "System Preferences"
get anchors of pane id "com.apple.preference.universalaccess"
end tell
which returned all of the available anchors. Here is a snippet:
...anchor TextToSpeech of pane id com.apple.preference.universalaccess, anchor Dwell of pane id com.apple.preference.universalaccess, anchor Dictation of pane id com.apple.preference.universalaccess, anchor Switch of pane id com.apple.preference.universalaccess, anchor Siri of pane id com.apple.preference.universalaccess...
I tried testing the applescript with other anchors (Dictation, Siri, etc) and they all worked (directed me to the intended area), but Switch doesn't. I even tried replacing "Switch" with its numerical value, reveal anchor 11 of pane id "com.apple.preference.universalaccess", but that also fails. Why is that? Also, how would I modify the applescript to get the intended result?
There appears to be a bug in that System Preferences will not properly reveal anchor "Switch" of pane id "com.apple.preference.universalaccess" and as such, here is a workaround.
Note that the coding in the example AppleScript code assumes that Switch Control has once previously been turned on manually so as to answer the initial System Preferences is trying to unlock Accessibility preferences dialog box where you have entered your User Name and Password then clicked the Unlock button.
The example AppleScript code, shown below, was tested in Script Editor under macOS Catalina and macOS Big Sur with Language & Region settings in System Preferences set to English (US) — Primary and worked for me without issue to click the Enable Switch Control checkbox.1
1 Assumes necessary and appropriate settings in System Preferences > Security & Privacy > Privacy have been set/addressed as needed.
and works for me to click the Enable Switch Control checkbox:
-- # Check to see if System Preferences is
-- # running and if yes, then close it.
-- #
-- # This is done so the script will not fail
-- # if it is running and a modal sheet is
-- # showing, hence the use of 'killall'
-- # as 'quit' fails when done so, if it is.
-- #
-- # This is also done to allow default behaviors
-- # to be predictable from a clean occurrence.
if running of application "System Preferences" then
try
tell application "System Preferences" to quit
on error
do shell script "killall 'System Preferences'"
end try
delay 0.1
end if
-- # Make sure System Preferences is not running before
-- # opening it again. Otherwise there can be an issue
-- # when trying to reopen it while it's actually closing.
repeat while running of application "System Preferences" is true
delay 0.1
end repeat
-- # Open System Preferences to the Accessibility pane.
tell application "System Preferences" to ¬
reveal pane id "com.apple.preference.universalaccess"
-- # Use System Events to achieve the goal.
tell application "System Events"
tell window 1 of application process "System Preferences"
-- # Wait for target pane to be available.
-- # The target in this case has a checkbox.
my waitForUIelement(checkbox 1)
-- # Ascertain the target row to select.
set rowSwitchControl to the first row of ¬
table 1 of scroll area 1 whose value of ¬
static text 1 of UI element 1 is ¬
"Switch Control"
-- # Select the target row.
select rowSwitchControl
-- # Wait for target checkbox to be available.
my waitForUIelement(checkbox 1 of tab group 1 of group 1)
-- # Click the Enable Switch Control checkbox.
click checkbox 1 of tab group 1 of group 1
end tell
end tell
delay 0.02
quit application "System Preferences"
-- ## Handler(s) ##
on waitForUIelement(uiElement)
tell application "System Events"
tell window 1 of application process ¬
"System Preferences"
set i to 0
repeat until exists uiElement
delay 0.1
set i to i + 1
if i ≥ 30 then return
end repeat
end tell
end tell
end waitForUIelement
Note: The example AppleScript code is just that and sans any included error handling does not contain any additional error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5, with the value of the delay set appropriately.

AppleScript in automator error ("The action "Run AppleScript" encountered an error ")

I wanted to find a way how to disable/enable hot corners via keyboard shortcut.
I found this apple script
property theSavedValues : {"Mission Control", "Desktop", "Dashboard", "Launchpad"} -- for example
tell application "System Preferences"
set current pane to pane id "com.apple.preference.expose"
tell application "System Events"
tell window "Mission Control" of process "System Preferences"
click button "Hot Corners…"
tell sheet 1
tell group 1
set theCurrentValues to value of pop up buttons
if theCurrentValues is {"-", "-", "-", "-"} then
repeat with i from 1 to 4
set thisValue to item i of theSavedValues
tell pop up button i
click
click menu item thisValue of menu 1
end tell
end repeat
else
copy theCurrentValues to theSavedValues
repeat with i from 1 to 4
tell pop up button i
click
click last menu item of menu 1
end tell
end repeat
end if
end tell
click button "OK"
end tell
end tell
end tell
quit
end tell
So I created an service in Automator with this apple script, attached it to keyboard shortcut, whenever I run this script in automator, it works but when i hit the shortcut, im getting "The action "Run AppleScript" encountered an error ".
Any ideas what can be done to fix this?
Thank you
Oh my god I feel so dumb, the only thing needed was to grant accessibility permission to app from which I'm using this service :).
You can do this by going to (Mac OS)Settings -> Security&Privacy -> Accessibility -> and finding the app from which you are running the service. (In my case it's Finder.)

Applescript - Close Pages Document Automatically

I am trying to create a script that will automatically close the frontmost window of Apple Pages.
on run {}
tell application "System Events"
if (window 1 of process "Pages" exists) then
try
tell application "Pages"
--display dialog "Hello World!" --TODO: remove, test code only.
--Keywords I have tried: file, document, window,
close window 1 saving no
end tell
--close window 1 of process "Pages" saving no
on error errMsg
display dialog "ERROR: " & errMsg
end try
end if
end tell
end run
Whenever I run this, it gives me the following error:
ERROR: Pages got an error: window 1 doesn’t understand the “close”
message.
I have looked at this article, and have used the following command:
sudo defaults write /Applications/Pages.app/Contents/Info NSAppleScriptEnabled -bool YES
However, it still fails to work. Any advice?
Details:
System Version: OS X 10.9.1 (13B42)
Kernel Version: Darwin 13.0.0
Pages: 5.0.1
If Pages isn't scriptable, you're kind of out of luck. If it were scriptable, you wouldn't need System Events to close a window; that kind of functionality is usually included in a scriptable app's dictionary.
System Events can help with apps that aren't scriptable, but you have to rely on the actual UI. But if that's the solution, you can't use tell application "Pages" for the inner block (like you have it); you have to use:
tell process "Pages"
If you go that route, now you have to use either the close button on window 1 or use the close menu command. Something like:
activate application "Pages"--note that this will probably be NECESSARY (if it's not frontmost, it prob won't work)
tell application "System Events"
tell process "Pages"
click menu item "Close" of menu "File" of menu bar item "File" of menu bar 1 of it
end tell
end tell
BUT then you have to come up with the problem of what happens if the window hasn't been saved (has been modified) -- which in a scriptable app uses the construction you were originally trying. When using System Events, you can do:
activate application "Pages"--note that this will probably be NECESSARY (if it's not frontmost, it prob won't work)
tell application "System Events"
tell process "Pages"
click menu item "Close" of menu "File" of menu bar item "File" of menu bar 1 of it
delay .5
keystroke "d" using command down
end tell
end tell
But then again how do you make the script smart enough to know if the window has been modified or not? Or maybe you use System Events to see if the window has been killed after the close command, and if it hasn't, it does the keystroke thing. This kind of thing can be done by doing something like:
activate application "Pages"
tell application "System Events"
tell process "Pages"
set frontMostWinName to name of window 1
click menu item "Close" of menu "File" of menu bar item "File" of menu bar 1 of it
tell me to delay 0.5
if exists window 1 then
if name of window 1 = frontMostWinName then keystroke "d" using command down
end if
end tell
end tell
I don't have Pages, but this works with another non-scriptable app, Bean (although I should mention that Bean uses tabs, and I had to move a tab to a window to get this to work*, and I don't know how Pages works in this regard).
[EDIT: *actually, this is not true; this works in Bean regardless of tabs/windows]

Auto click a dialog button using AppleScript

I want to use AppleScript to auto login for a web by Safari.
When I open a URL and give username and password, if it is the first time or hasn't saved the password yet, it will show message: "Would you like to save this password?".
I want to use AppleScript to choose "Not now". How can I do that?
Here is my current code:
tell application "Safari"
open location "http://www.amazon.com"
activate
end tell
if page_loaded(60) then
say "Page Loaded"
tell application "Safari"
set loginURL to do JavaScript "document.getElementById('nav-your-account').getAttribute('href')" in document 1
open location loginURL
end tell
else
say "Page Failed to load or Safari didn't open"
end if
if page_loaded(60) then
say "Page Loaded"
tell application "Safari"
do JavaScript "document.getElementById('ap_email').value = 'mritjp'; document.getElementById('ap_password').value = 'mritjp'; document.forms['signIn'].submit();" in document 1
---HOW TO CONTROL TO CHOOSE "Not Now" in message "Would you like to save this password?" of safari
activate
delay 2
end tell
else
say "Page Failed to load or Safari didn't open"
end if
on page_loaded(timeout_value) -- in seconds
delay 1
repeat with i from 1 to timeout_value
tell application "Safari"
if name of current tab of window 1 is not "Loading" then exit repeat
end tell
delay 1
end repeat
if i is timeout_value then return false
tell application "Safari"
repeat until (do JavaScript "document.readyState" in document 1) is "complete"
delay 0.5
end repeat
end tell
return true
end page_loaded
Fixed by comment of Lauri Ranta:
If access for Assistive Devices has been enabled from System Preferences, you can use System Events:
on enabledGUIScripting()
do shell script "sudo touch /private/var/db/.AccessibilityAPIEnabled" password "1" with administrator privileges
end enabledGUIScripting()
Then:
tell application "System Events" to tell process "Safari"
click button 3 of sheet 1 of window 1
end tell
If access for assistive devices has been enabled from System Preferences, you can use System Events:
tell application "Safari"
do JavaScript "document.getElementById('login_button_id').click()" in document 1
end tell
delay 1
tell application "System Events" to tell process "Safari"
click button 3 of sheet 1 of window 1
end tell

Applescript setting ip address

I wanted to automate the process of changing my ip address using apple-script. So i wrote a script that will automatically do that, But i have problems in setting up the ip address.
set ipAddress to "192.168.110.48"
tell application "System Preferences"
activate
set current pane to pane id "com.apple.preference.network"
end tell
tell application "System Events"
tell process "System Preferences"
click checkbox "Click the lock to make changes." of window "Network"
tell application "System Events" to keystroke "p"
tell application "System Events" to keystroke "a"
tell application "System Events" to keystroke "s"
tell application "System Events" to keystroke "s"
tell application "System Events" to keystroke "w"
tell application "System Events" to keystroke "o"
tell application "System Events" to keystroke return
click button 11 of window "Network"
tell window "Network"
tell sheet 1
tell tab group 1
click radio button "TCP/IP"
set contents of text field 2 to ipAddress
end tell
end tell
end tell
end tell
end tell
Everything executes fine except for this statement
"set contents of text field 2 to
ipAddress"
I am getting the following error:
error "System Events got an error:
Can’t set contents of text field 2 of
tab group 1 of sheet 1 of window
\"Network\" of process \"System
Preferences\" to \"192.168.110.48\"."
number -10006 from contents of text
field 2 of tab group 1 of sheet 1 of
window "Network" of process "System
Preferences"
I checked the UI elements using UIBrowser so i am sure that i am using the correct elements.
What is causing the problem? and Also can u tell a better way to write the same thing?
An alternative solution for changing IPs would be to use the network locations feature of the Network pane and use predefined locations.
If you click on the Network pane in Systems Preferences at the top you will see a pull down menu titled Location. Click that and choose Edit Locations...
Then you can create a new location and configure an interface whether it be ethernet, airport, firewire, 3G card, etc. You can have multiple locations for the same interface. So, you could have an ethernet location with an IP of 192.168.2.2 and then you could have another set to 192.168.2.3 and so on...
Once you have all of the new locations created and labeled then you can use AppleScript to toggle between them.
To get your current network location in AppleScript use the following code:
set currentLocation to do shell script "networksetup -getcurrentlocation"
To select a new location use the following AppleScript code:
set newLocationName to "whatever location you want to choose"
do shell script "scselect " & newLocationName with administrator privileges
Using the above method you can create numerous predefined network locations and toggle between them easily with your AppleScript. In addition, you could create a random function that will randomly select from an AppleScript list which is populated with all of your locations.
Use the networksetup shell script to manually setup your IP:
do shell script "networksetup -setmanual Ethernet 192.168.110.48
255.55.255.0 192.168.110.1 password YOURPASSWORD with administrator privileges"
To go back to DHCP:
do shell script "networksetup -setdhcp Ethernet YOURPASSWORD
with administrator privileges"
Of course you can manipulate the string to use variables and change "Ethernet" to any interface (like Wi-Fi).
This is a keyword error.
set contents of text field 2 to ipAddress is not a proper command
the right command is
set value of text field 2 to ipAddress
Enjoy yourself!

Resources