Run apple script after mac resumes from sleep mode - macos

I want my macbook to run a script each time it resumes from sleep mode.
My code is extremely simple:
tell application "Finder"
if exists (disk "HDD") then
do shell script "diskutil eject HDD"
else
do shell script "diskutil mount HDD"
do shell script "diskutil eject HDD"
end if
end tell
I have a second HDD installed in the cd-rom bay and each time I resume from sleep mode I can hear the drive spinning even though it's current state is not mounted. But forcing a mount/eject command on the drive solves this issue. The only drawback is that I have to do this manually; which now I want to overcome.
Could someone help me on this matter?

There are several options in this page:
https://apple.stackexchange.com/questions/27036/possible-to-run-scripts-on-sleep-and-wake
It seems that the Scenario app could be of some help-

Related

Access built-in Power Manager? states

Im trying to write a super simple applescript that will launch the OneDrive App, or ensure it is open, whenever the machine's power source is set to plugged in, and will quit, or make sure is closed, when the power source is set to battery.
I'm having trouble finding how to access the built-in "power indicator" in Yosemite. All of my searches lead to old, irrelevant results from years ago.
Edit: I think I will have to use a do shell script within the applescript using pmset -g batt
Now drawing from 'AC Power'
-InternalBattery-0 100%; charged; 0:00 remaining
And parse this result, but I am not sure how.
Edit: Here it is for anyone in the future who may want something similar:
global appName
on appIsRunning()
tell application "System Events" to (name of processes) contains appName
end appIsRunning
on acIsConnected()
return (do shell script "system_profiler SPPowerDataType | grep -q 'Connected: Yes' && echo \"true\" || echo \"false\"") as boolean
end acIsConnected
on toggleApp()
if my acIsConnected() then
if not my appIsRunning() then
tell application "Finder"
open application file (appName & ".app") of folder "Applications" of startup disk
end tell
end if
else
tell application appName
quit
end tell
end if
end toggleApp
-- This will only be executed once.
on run
set appName to "OneDrive"
end run
-- This will be executed periodically, specified in seconds, every return.
on idle
my toggleApp()
-- Execute every 2 minutes.
return 120
end idle
-- Not mandatory, but useful for cleaning up before quiting.
on quit
-- End handler with the following line.
continue quit
end quit
Here is a one-liner that polls for connected status, since I guess you can have less than 100% and still be connected (charging).
set acConnected to (do shell script "system_profiler SPPowerDataType |grep -q 'Connected: Yes' && echo \"true\" || echo \"false\"") as boolean
Here's another one liner...
set acConnected to last word of paragraph 1 of (do shell script "ioreg -w0 -l | grep ExternalChargeCapable")
If you are happy to use a third party tool, you can avoid polling for the battery state. This will make your script more efficient.
Power Manager can run AppleScripts when the battery state changes. How to Run a Command When Switching to Battery Power, walks through how to set this up for scripts.
Swap out the #!/bin/sh for #!/usr/bin/osascript in the script, and you can use AppleScript.
Disclaimer: I wrote Power Manager and can answer comments about how it works.
Provided you have battery icon on screen's top right:
tell application "System Events" to tell process "SystemUIServer" ¬
to value of attribute "AXDescription" of ¬
(first menu bar item whose value of attribute "AXDescription" ¬
begins with "Battery") of menu bar 1
You get "Battery: Charged" or "Battery: Calculating Time Remaining… " or something else

Applescript: Making a self-quitting script

I have an applescript which launches an application on computer startup.
The problem is that the script stays open in the background and prevents the machine from restarting, unless I force-quit the said script (The script is saved as an application).
How do I make the script quit itself after performed the actions?
Here is what I have (On OSX 10.8):
on run
do shell script "#!/bin/sh
# luxconsole control
/Applications/LuxRender/LuxRender.app/Contents/MacOS/luxconsole &"
quit
end run
Thanks.
Try this way:
on run
do shell script "/Applications/... > /dev/null 2>&1 &"
quit
end run
Try This;
do shell script "killall -yourapp-"
put that at the end of your script

Script to shutdown mac

I'm trying to automate the shutdown of my mac, I've tried the scheduled shutdown in energy saver and I wanna sleep but these don;t seem to work. VLC player runnign seems to prevent the shutdown. I think I need a script to forcefully shutdown the mac regardless of of what errors may thrown to screen by various programs running.
Thanks
Ok,
This is the applescript code im using to shutdown may mac. I've added it as an iCal event thats runs nightly.
tell application "System Events" to set the visible of every process to true
set white_list to {"Finder"}
try
tell application "Finder"
set process_list to the name of every process whose visible is true
end tell
repeat with i from 1 to (number of items in process_list)
set this_process to item i of the process_list
if this_process is not in white_list then
do shell script "killall \"" & this_process & "\""
end if
end repeat
on error
tell the current application to display dialog "An error has occurred!" & return & "This script will now quit" buttons {"Quit"} default button 1 with icon 0
end try
tell application "System Events"
shut down
end tell
Could you try a simple applescript, which goes something like this...
tell application "System Events"
shut down
end tell
See if it works, and then you can make it run through Automator at certain time, etc.
my solution (somwhat late). Just a bash script with apple in it:
#!/bin/bash
# OK, just shutdown all ... applications after n minutes
sudo shutdown -h +2 &
# Try normal shutdown in the meantime
osascript -e 'tell application "System Events" to shut down'
I also edited the /etc/sudoers (and /private/etc/sudoers) file(s) and added the line:
ALL=NOPASSWD: /sbin/shutdown
Always worked for me for an assured shutdown (knock knock ;-) )
This should do:
do shell script "shutdown" with administrator privileges
If you want to pass the admin password from key chain, with no prompt:
do shell script "shutdown" with administrator privileges password "password here"
But do not store the admin password in clear anywhere. Instead use the keychain access.
Alternatively you could kill all user processes, via:
do shell script "kill -9 -1"
This however would also kill your own Applescript process, preventing it from requesting the shutdown/restart afterwards.
Either way you're playing with fire, when using sudo or kill.
do what linux users do. use a bash script. if u dont know how to create one just go ahead and download ANY bash script u find using your internet search and open it with text edit app and paste the following:
( be careful if many people use the pc , then this method is not recommended, cause they can learn your user login password from inside this script )
#!/bin/bash
echo -n "Enter a number > "
read x
echo [your password] | sudo -S shutdown -h +$x
it will work the same way it works in linux. the terminal will pop up a message and ask you to enter a number. if we choose for exaple 50 , then the pc ( niresh ) or mac will shutdown in 50 minutes.

Setting expiration time when script tries to mount a network drive

The start up script bellow mounts a network drive in my macbook:
try
tell application "Finder"
mount volume "afp://iMac-01._afpovertcp._tcp.local/Backup%20HD"
end tell
end try
There is two problems with this script for me:
If I am out of the local network that the network drive is located, the script takes a long time trying to connect with it, and makes my macbook slowly in initialization. So, how to setup a maximum time for the script try to connect with the network drive?
If the network drive cannot be connected, a message warning me of that pops out. How to ignore this message? i.e, make it not appears.
I'm never made an apple script before of that, so please, if it is possible, help me modifying the original script.
Thanks in advance.
use 'with timout'
try
with timeout of x seconds
tell application "Finder"
mount volume "afp://iMac-01._afpovertcp._tcp.local/Backup%20HD"
end tell
end timeout
end try
to answer your questions:
1: use with timeout as mcgrailm states; however try just writing
with timeout of 2 second --no plural
<your code here>
end timeout
2: the dialog that pops up is a finder popup and as such your script cannot see that, the "try on error" never gets called as the error is never returned to the script, so if you want to automate the click on ok then this code will work. This code will click the button after your timeout seconds.
try
<your code here>
on error
tell application "System Events"
keystroke return
end tell
end try
i have also included my version of the same idea which i use at home this script does a check of the network, then tries to mount the volume using a shell mount. i originally used a finder "mount volume" with timeout and that codes exists as inline comments too, but I didn't like the dialog popping up on errors; even if only for a second, so i moved on to shell script.
--------------------------------------------------------------------------------------
--"Basic Drive Mounter.app"
try
set IP_address to "xxx.xxx.xxx.xxx"
set IP_Valid to true
try
do shell script ("ping -c 2 " & IP_address)
on error
set IP_Valid to false
end try
if IP_Valid then
tell application "Finder"
if disk "work" exists then
else
try
do shell script "mkdir /Volumes/work"
end try
do shell script "mount_afp afp://xxx.xxx.xxx.xxx/work /Volumes/work/"
-->>finder mount volume version
--with timeout of 2 second
-- mount volume "afp://xxx.xxx.xxx.xxx/work"
--end timeout
--<<finder mount volume version
end if
end tell
end if
on error
return 0
-->>finder mount volume version
--on error finder returns an error dialog which needs to be closed to go back and retry
--tell application "System Events"
-- keystroke return
--end tell
--<<finder mount volume version
end try
--------------------------------------------------------------------------------------

How can I detect if the screen is locked or screensaver is active from the Terminal in OS X 10.6?

Due to the new limitations of Kerberos in OS X 10.6, I'm working on a script that offers similar functionality to what used to be available in 10.5. Essentially it parses the klist output to see if your ticket is expiring and displays how long until it expires. If we hit the 10 minute mark, it calls kinit to do a GUI password prompt to ask for your kerberos password. If the ticket is expired it does the same thing.
The script makes sure that kinit is not running before calling it again so we don't have multiple kinit calls, and the script works really great (called out of GeekLog so you can see the status). Problem is this morning my system was giving the spinning beachball when I went to unlock the screen. I am suspecting my script and/or kinit from doing something; the machine was available via ping, but otherwise unresponsive to ssh or AFP.
So what I want to do is detect whether or not the screen is locked or the screensaver is engaged. I've found that on previous versions of OS X, you could grep for ScreenSaverEngine to determine whether it was active or not, but that doesn't seem to be the case any longer.
So how can I determine if the screen is locked or otherwise engaged using commandline tools? If the screen is locked, I want the script to simply exit so it doesn't bother with the klist or try to do a kinit. I'm hoping that will prevent the lockup I experienced this morning. Any ideas?
A bit of a kludge but you can easily query the System Events background app via Apple Events to tell if a screen saver is running. For example:
$ osascript -e 'tell application "System Events"' \
> -e 'get running of screen saver preferences' \
> -e 'end tell'
false
$ # engage screen saver after starting next command
$ sleep 5; osascript -e 'tell application "System Events"' -e 'get running of screen saver preferences' -e 'end tell'
true
$
You probably really need to find out why you're getting the lock up, though.
Just out of curiosity, have you tried ssh'ing into the OS X machine and compare the process list before/after the screen saver / lock ?
That's what I'd try.

Resources