Using launchd to send an email on startup and shutdown

Hello All !
I'd like to get an email whenever my Mac starts up and shuts down, since I have to leave it unattended for quite some long periods of time (and even with the help of a UPS, power goes out anyway...). My Mac runs under Mac OS X Lion.
I found some help on the Internet, mainly from this page : http://www.syntaxtechnology.com/2009/06/email-on-shutdown-and-restart/ , which applies to Linux, and hoped it could work on Mac OS X (I thought at first I could just drop a script in something like /etc/init.d/ or /etc/rc.d/rc5.d but well... we have launchd instead...).
The first method listed in the page above worked well, but sends an email only on startup (for a reminder: you add a line that starts with @reboot in your crontab, and a command that sends directly an email).
I then tried to adapt the second method to Mac OS X, and succeeded partially: I wrote a small script based on what was shown on that page (a start and stop function, start gets called when the script is started, and stop gets called based on a trap on various kill signals, with an infinite wait loop: see below). I also wrote the plist file, loaded it in launchd and rebooted my Mac several times to test everything.
I get an email on each startup (yeah!), but the shutdown mail gets sent only at the next startup. So I guess that postfix gets killed by the shutdown process *before* being able to send my shutdown email :-(
So here are my main questions, if someone can help me:
1. is there a way to precisely call a script during the shutdown process, meaning giving it a priority so it gets called before postfix dies ? (like the rc directories and the naming conventions (KnnScriptName and SnnScriptName) found on some Linux/Unix).
2. is it possible to do that with launchd ? if not, what would be the Mac OS X sanctionned way of doing this ?
Other things:
3. my shell script writing ability is kind of rusty, so maybe I made some "very bad shell writingTM": l'm not sure putting an infinite while loop with a 15 second pause in it is the best way of telling a script to do nothing. There might other things in there that would make an Unix guru jump out of his chair: please tell me :-)
This is my plist:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC “-//Apple Computer//DTD PLIST 1.0//EN” “http://www.apple.com/DTDs/PropertyList-1.0.dtd”>
<plist version=“1.0”>
<dict>
<key>Disabled</key>
<false/>
<key>Label</key><string>org.amarante.startshutemail</string>
<key>ProgramArguments</key>
<array>
<string>/Library/Scripts/startshutemail-launchd.sh</string>
<string>start</string>
</array>
<key>RunAtLoad</key><true/>
</dict>
</plist>
And this is the script that does the job:
#!/bin/bash
# PHL 20120604 startshutemail-launchd.sh
# Send an email on startup and shutdown (version for launchd)
# Based on script and explanations found here:
# http://www.syntaxtechnology.com/2009/06/email-on-shutdown-and-restart/
# Modification history
# PHL 20120604 v01 First version
# Environment variables #################################################
DEST_EMAIL="[email protected]"
SRV_NAME=Amarante
EVENT_TIME=$(date +%Y/%m/%d-%H:%M:%S)
RESTART_SUBJECT="[$SRV_NAME] $EVENT_TIME : System Startup"
RESTART_BODY="This is an automated message to notify you that $SRV_NAME started successfully at $EVENT_TIME."
SHUTDOWN_SUBJECT="[$SRV_NAME] $EVENT_TIME : System Shutdown"
SHUTDOWN_BODY="This is an automated message to notify you that $SRV_NAME is shutting down now ($EVENT_TIME)."
# Functions ##########
stop()
echo "$SHUTDOWN_BODY" | mail -s "$SHUTDOWN_SUBJECT" $DEST_EMAIL
return 0
start()
echo "$RESTART_BODY" | mail -s "$RESTART_SUBJECT" $DEST_EMAIL
return 0
# Main part #########
case $1 in
stop)
stop
start)
start
esac
# trap kill signals to send an email
trap stop HUP INT QUIT ABRT KILL ALRM TERM TSTP
# sleep until killed
while :
  do
    sleep 15
  done
Thanks for your help, and any comment :-)
Paul-Henri

Thanks a lot for your answer, Camelot, even if it sorts of confirm what I suspected. Pinging a machine from an external observer is a solution, but it will also report broken links problems and not only a computer shutting down, and it raises the next tier of problems, general network reliability after individual system reliability. It's something I'll have to look at for sure.
It's weird there isn't any way to access the way the shutdown process works.
One of the commenters (#14) on the page from Syntaxtechnology had a similar problem: he added a "sendmail -q" in his script to force sendmail to go to work and service the queue before shutting down, which I can try, but he also added a delay to the stop process of sendmail, which is something I'm not sure I can do on Mac OS X (and that might disappear one day with one of the OS updates).
Unless there is a way to change the launchd.plist file for postfix and add an ExitTimeOut option in it (I found this idea here : https://discussions.apple.com/message/17229690#17229690 )
Cheers,
Paul-Henri

Similar Messages

  • HELP. Using iCal to send timed emails - I used to be able to do this...

    Ok - there's a chance I've gone completly mad - or I just dreamt this - but: Once upon a time I used iCal to send timed emails (with Mail) to outside addresses without the emails looking like they came from iCal.
    I did this for things like 'calling' in sick to work (therefor looking like I was up at 8:15 being ill, instead of sleeping comfortably in hung over splendor) or sending out parts of work throughout the workday (instead of when I'd actually completed them at three in the morning).
    This was very useful.
    I just can't now figure out how I did this.
    Has one of the iCal updates removed this function? Is there something obvious I've forgotten?
    I seem to remember using iCal to trigger a file that in turn sent the email - but again I can't trust my memory.
    Anyone have any hints or ideas? I'm driving my self mad on this one.

    Neal,
    I am in the same predicament. I would essentially like to accomplish the same deal, as seen below. . . (from another forum that went unanswered.)
    I use iCal (1.5.5/ 2.0.3) currently but own Entourage (11.2.1) as well. I have clients that I service on a weekly or biweekly basis whose appointments are in my iCal; I call and remind them the day before. The majority of these people are great about checking email. I would like to set up an automated email reminder which is sent to them for each appointment, two days in advance that does not contain an .ics file. Many times my clients' email app has junked the message due to the small attachment. Others don't want to open a file when they don't know what it is.
    Predetermined timed stamped/Automated iCal events are possible aren't they?! If not, do I have to move over to :dreaded Entourage?

  • I am trying to send an email to myself and BCC everyone in my address, but have forgotten how. Can someone help me with this?

    I am trying to send an email to myself and bcc everyone in my address book, but have forgotten how. Can anyone help me with this? Thanks.

    http://chrisramsden.vfast.co.uk/7_How_do_I_send_to_everyone.html

  • Would like to use iMessages internationally, sending between an iPod touch and and iPhone. Does anyone know if it will work between countries?

    Would like to use iMessages internationally, sending between an iPod touch and and iPhone. Does anyone know if it will work between countries?

    The iPhone is not user servicable. You can get an out of warranty replacement from Apple for $149. If you open the phone yourself, you forfeit the ability to do this.

  • Which AD Attributes are use to store Send-As, Full-Access permissions and Calendar permissions?

    Hello All,
    Please, could someone tell me Which AD Attributes are use to store Send-As, Full-Access permissions and Calendar permissions?
    Regards
    José Osorio

    Hi Jose,
    Based on my test, the value of attribute msExchDelegateListLink points to Full Access permission while the
    publicDelegates indicates Send on behalf permission.
    As for Send as permission, it is the permission in the Access Control List which is a list of permissions attached to an object. Just like:
    Thanks,
    Winnie Liang
    TechNet Community Support

  • How do i send an email to addressee and receive back a confirmation that the addressee received my email?

    how do i send an email to addressee and receive back a confirmation that the addressee received my email?

    Even if you find a way to send the request for a read confirmation with the email, you are dependent on the recipient's mail system and/or mail reading software to notice it and comply with it. Many do not do so, either because they cannot or because somebody has disabled (or not enabled) the feature.

  • When I send an email with attachments and open them on my ipad some of them open but others do not

    When I send an email with attachments and open them on my ipad some of them open but others do not

    What are the types that won't open?
    Do you have an App that can open those types of files?

  • Shell Script  for Startup and Shutdown the database

    Hi,
    i want Shell Script for Startup and Shutdown the database in Solaries.
    could any one can hep me where i can get this script. or send to me to [email protected]
    Thanks & Regards,
    Gangi reddy

    SHUTDOWN
    SHUTDOWN ABORT]
    Shuts down a currently running Oracle instance, optionally closing and dismounting a database.
    Terms
    Refer to the following list for a description of each term or clause:
    ABORT
    Proceeds with the fastest possible shutdown of the database without waiting for calls to complete or users to disconnect.
    Uncommitted transactions are not rolled back. Client SQL statements currently being processed are terminated. All users currently connected to the database are implicitly disconnected and the next database startup will require instance recovery.
    You must use this option if a background process terminates abnormally.
    IMMEDIATE
    Does not wait for current calls to complete or users to disconnect from the database.
    Further connects are prohibited. The database is closed and dismounted. The instance is shutdown and no instance recovery is required on the next database startup.
    NORMAL
    NORMAL is the default option which waits for users to disconnect from the database.
    Further connects are prohibited. The database is closed and dismounted. The instance is shutdown and no instance recovery is required on the next database startup.
    TRANSACTIONAL [LOCAL]
    Performs a planned shutdown of an instance while allowing active transactions to complete first. It prevents clients from losing work without requiring all users to log off.
    No client can start a new transaction on this instance. Attempting to start a new transaction results in disconnection. After completion of all transactions, any client still connected to the instance is disconnected. Now the instance shuts down just as it would if a SHUTDOWN IMMEDIATE statement was submitted. The next startup of the database will not require any instance recovery procedures.
    The LOCAL mode specifies a transactional shutdown on the local instance only, so that it only waits on local transactions to complete, not all transactions. This is useful, for example, for scheduled outage maintenance.
    Usage
    SHUTDOWN with no arguments is equivalent to SHUTDOWN NORMAL.
    You must be connected to a database as SYSOPER, or SYSDBA. You cannot connect via a multi-threaded server. For more information about connecting to a database, see the CONNECT command earlier in this chapter.
    http://download-west.oracle.com/docs/cd/B10501_01/server.920/a90842/ch13.htm#1013607
    Joel Pérez

  • Spontaneous startups and shutdowns

    Ever since I got my G5 in 2004, I've had spontaneous startup/shutdown problems. I will wake up in the morning or come home from work and find the computer on and at the login prompt (I have set no such predetermined startup time.) Or, I'll be working and all of a sudden it powers down and then powers back up (it will bring me back to the same screen and what I was doing), but after repeated occurrences of shutdown/startup, usually in short succession, it will permanently shut down, requiring me to shut off the battery backup into which it is plugged to reset the whole system. Then things settle down for a while. Then a month or two later, it will go through another bad spate of spontaneous startups and shutdowns, almost like it just got over a cold only to contract a new one.
    At first, Apple said it was a motherboard problem which they replaced; that didn't solve my problem. Then they said it was a bad video cable to the monitor and repaired that; that didn't solve my problem, either. They asked if I had any peripherals (printer, scanner, external HD) hooked up and said such items can cause erratic behavior (to which I felt like asking "then why do you manufacture your computers with ports in them so users CAN plug in other devices?") I've given up taking it to them because I can't make it replicate its erratic behavior and unless they see what it's doing, they can't do anything about it (and I don't think they really believe me, anyway...)
    I've reset my PRAM. I've reset my SMU (actually that happens every time I shut down the computer because I shut down the battery backup every time to prevent unsupervised morning startup.) I've run Disk Warrior. I've checked and confirmed my power source. I've literally unplugged everything (and I mean EVERYTHING) and re-connected all components. All to no avail. I even have video of it happening because Apple doesn't believe what I'm describing. Is it possible that my computer has been infected and is one of those "slave computers" that hackers use to do their bidding? I've wondered about that...
    Has anyone else experienced this?

    It almost sounds like a bad UPS.
    Have you tried bypassing the UPS? What is the rating of the thing?

  • Startup and shutdown of 11i Services in windows

    Hi friends, I am new for windows.
    how can we startup and shutdown of 11i instacne under windows.
    can we do it through services screen
    or
    can we do it through scripts as we do it on Unix/Linux
    which is the best method

    Either way is fine. Use the method which you feel if more comfortable to you. But I would suggest keep using scripts, as in future if you move to other platform you will not get surprised.
    Thanks
    Sundeep
    http://troubleshootingappsdba.blogspot.com

  • Startup and shutdown from command line with version 9i

    Hi, i'm an Oracle newbie. I heard it's possible to startup and shutdown an oracle (instance? or database? which one is it) from the command line.
    A little background on what it is that I want to do:
    I'm looking to backup a database by copying the files that make up the database to a location from where they will be commited to tape media. To do this I must shutdown the database, copy the files, and startup the database again.
    At the moment the backups are full exports which I find unnecessary since it is a development database which is never used at night. It is therefore not an issue if we want to shut it down and re-start it after a few minutes. (I think it would take longer to export as opposed to copy the files right?)
    I need help and advice :
    1. Is my way of going about this correct ?
    2. How do I startup/shutdown from the command line (sqlplus user/password command) or should I use another utility ?
    Thanks,
    Gabriel

    set oracle_sid=ORCL ==> your database namethis is NOT always true. It's instance name. usually, we set instance name is same as database name.But we also can set instance name is different from database name.
    for example.
    C:\>oradim -new -sid abc123
    C:\>set ORACLE_SID=abc123
    C:\>sqlplus /nolog
    SQL*Plus: Release 9.0.1.4.0 - Production on Tue Jun 20 22:40:59 2006
    (c) Copyright 2001 Oracle Corporation.  All rights reserved.
    SQL> conn / as sysdba
    Connected to an idle instance.
    SQL> startup pfile=E:\ora901DB\admin\init.ora
    ORACLE instance started.
    Total System Global Area  344748244 bytes
    Fixed Size                   282836 bytes
    Variable Size             184549376 bytes
    Database Buffers          159383552 bytes
    Redo Buffers                 532480 bytes
    Database mounted.
    Database opened.
    SQL> select name from v$database;
    NAME
    DB901
    SQL> select instance_name from v$instance;
    INSTANCE_NAME
    abc123

  • Startup and Shutdown class not found

    Hi, I try to use a startup and shutdown class on my WLS, but on startting show
    this exception : weblogic.t3.srvr.FatalStartupException ... class failure post_java.class
    , java.lang.ClassNotFoundException
    the post_java.class is in .\mydomain\lib the same of weblogic.jar, in startWebLogic.cmd
    is add it on classpath
    Where is the place of Startup and Shutdown class ?
    I use WLS 6.1 sp3 on Windows and UNIX (Soalris)
    Tanks.

    Hi.
    You need to add the directory where you have your startup class to your classpath. The
    weblogic.jar file is named specifically in the classpath, so it's not enough to put your
    classpath in the ./mydomain/lib directory.
    The easiest thing to do would be to add ./mydomain/lib to your classpath in your start script.
    Regards,
    Michael
    Roberto Hernandez wrote:
    Hi, I try to use a startup and shutdown class on my WLS, but on startting show
    this exception : weblogic.t3.srvr.FatalStartupException ... class failure post_java.class
    , java.lang.ClassNotFoundException
    the post_java.class is in .\mydomain\lib the same of weblogic.jar, in startWebLogic.cmd
    is add it on classpath
    Where is the place of Startup and Shutdown class ?
    I use WLS 6.1 sp3 on Windows and UNIX (Soalris)
    Tanks.

  • Startup and shutdown sequence in MSCS clustered EP

    Hi,
    We are running an Enterprise portal in a clustered environment with 2 nodes (HA). Please advice the best practice
    on startup and shutdown order and procedures for the instances, SCS, CI and database and cluster (nodes).
    This is essential for maintenance and patching.
    Thanks and regards,

    Hi, 
    Your wish you can stop using cluster manager or using script.
    You should always shut your central instance lastly,enque server should be also shutdown before the central instance,as far as i know.
    Regards,
    Vamshi.

  • Startup and Shutdown scripts for OCS 9.0.4 on Windows?

    Hi,
    I wanted to know if startup and shutdown scripts for OCS 9.0.4 on Windows are available.
    I am thinking something like the ocsctl_sample scripts that OCS10g included.
    I have checked the OCS 9.0.4 documentation and not a lot of information for the windows platform is avaiable.
    Any information will be appreciated.
    Thanks,
    Ana

    There is no scripts that comes with 9.0.4.
    One possibility is to just write the commands you normally use in a batch-file, but note that then you have no checking, and if OCS runs on several machines you should have some checking for required processes etc.
    We are using some scripts that does this, but I'm not shure where they came from, possibly from Metalink or from this forum. Try a search. Our scripts are changed quite a bit for our needs, but I might be able to find the original ones.

  • How to write triggers on startup and shutdown of the server?

    Plz advice.
    How to write triggers on startup and shutdown of the server?
    I could write it but nothing happened!!!

    Small code example for you:
    [email protected]> @ connect mob/mob
    [email protected]> create or replace trigger shutdown_trigger
    2 before shutdown on database
    3 begin
    4 insert into shut_table values(sysdate);
    5 end;
    6 /
    Trigger created.
    [email protected]> create or replace trigger start_trigger
    2 after startup on database
    3 begin
    4 insert into start_table values(sysdate);
    5 end;
    6 /
    Trigger created.
    [email protected]> @ connect "/ as sysdba"
    [email protected]> shutdown immediate
    Database closed.
    Database dismounted.
    ORACLE instance shut down.
    [email protected]> startup
    ORA-32004: obsolete and/or deprecated parameter(s) specified
    ORACLE instance started.
    Total System Global Area 64036368 bytes
    Fixed Size 454160 bytes
    Variable Size 50331648 bytes
    Database Buffers 12582912 bytes
    Redo Buffers 667648 bytes
    Database mounted.
    Database opened.
    [email protected]> select * from mob.start_table;
    START_DAT
    14-SEP-06
    [email protected]> select * from mob.shut_table;
    SHUT_DATE
    14-SEP-06
    Best Regards
    Krystian Zieja / mob

Maybe you are looking for

  • My iPhone4 loses signal and when I do hard reset, I can't send or receive SMS and calls. I have to back-up and restore weekly!

    It started last month before I ungraded to iOS5. So my network provider advised me to upgrade. It fixed the problem but it happens again after several days. I lose signal then when I do hard reset, signal is back but I can't send or receive SMS or ma

  • ADOBE PHOTOSHOP ELEMENTS 1.0.1

    Tengo un nuevo ordenador con Windows 7 que incorpora Internet Explorer 10. Con la compra de una cámara fotográfica Minolta Z10 incluía el programa ADOBE PHOTOSHOP ELEMENTS 1.0.1 con su nº de serie. En el ordenador nuevo cuando inicio la instalación d

  • Opening a word file from oaf page

    Hello all, we have a word file which we need to open from OAF page. Is it possible to achieve this using personalization? If yes, please give me the steps. If not, we we need to go for customization to achieve this, whichis the approach on that? Than

  • My mdp to hdmi adapter stopped working properly

    The adapter worked fine on my 2010 MacBook Pro. I recently changed to a 2012 MacBook Pro and now the same adapter isn't working anymore. Is it something to do with the latest Mavericks 10.9.2 update??.

  • CD looks like it burns but doesn't work

    I'm just upgraded to Itunes 11.4.0.18.  I put a free podcast in a playlist, used blank CD-R, did the Burn to Disk, Audio CD.  When I start it, it goes through the whole process, it counts down, the CD drive makes its little noises, and finalizes the