Sending Growl messages over a network with Python

6-6-12 – This script is really old and may not work with current versions of Growl. There are some good libraries to choose from and I’d recommend looking at them instead.

Updated 12-4-10 – minor code updates
I have yet another script. This one is actually my first one in Python, which is kind of sad after all the good things I’ve heard about the language. This time I didn’t actually write the entire script – I simply added to one that had already been written to give it more functionality.

The original script was found here: and almost all credit goes to it’s author, as I only added a little bit more to it.

What this version does is send a Growl message over UDP to a Mac (running Growl and configured to listen for incoming notifications) using Python. I thought this was really cool – I could script my remote Linux machines (or whatever OS) to send messages to my main Mac.

What I added was the ability to have command line arguments so that it would be easier to change options on the fly and also easier to script.

Running ./ -h will give you the following:

#!/usr/bin/env python

# Updated 12-4-2010
# Altered 1-17-2010 - Tanner Stokes -
# Added support for command line arguments

# """Growl 0.6 Network Protocol Client for Python"""
# __version__ = "0.6.3"
# __author__ = "Rui Carmo ("
# __copyright__ = "(C) 2004 Rui Carmo. Code under BSD License."
# __contributors__ = "Ingmar J Stein (Growl Team), John Morrissey (hashlib patch)"

  import hashlib
  md5_constructor = hashlib.md5
except ImportError:
  import md5
  md5_constructor =

import struct
# needed for command line arguments
import sys
import getopt

from socket import AF_INET, SOCK_DGRAM, socket


def main(argv):

    # default to sending to localhost
    host = "localhost"
    # default title
    title = "Title"
    # default description
    description = "Description"
    # default priority
    priority = 0
    # default stickiness
    sticky = False

    # if no arguments are given, show usage
    if(len(argv) < 1):

        opts, args = getopt.getopt(argv, "hH:t:d:p:s")
    except getopt.GetoptError:
    for opt, arg in opts:
        if opt in ("-h"):
        elif opt in ("-H"):
            host = arg
        elif opt in ("-t"):
            title = arg
        elif opt in ("-d"):
            description = arg
        elif opt in ("-p"):
            # acceptable values: -2 to 2
            priority = int(arg)
        elif opt in ("-s"):
            sticky = True

    # connect up to Growl server machine
    addr = (host, GROWL_UDP_PORT)

    s = socket(AF_INET,SOCK_DGRAM)
    # register application with remote Growl
    p = GrowlRegistrationPacket()
    # send registration packet
    s.sendto(p.payload(), addr)

    # assemble notification packet
    p = GrowlNotificationPacket(title=title, description=description, priority=priority, sticky=sticky)

    # send notification packet
    s.sendto(p.payload(), addr)

def usage():
    print """Usage: ./ [-hs] [-H hostname] [-t title] [-d description] [-p priority]
Send Growl messages over UDP
  -h help
  -H specify host
  -t title
  -d description
  -p priority [-2 to 2]
  -s make sticky"""

class GrowlRegistrationPacket:
  """Builds a Growl Network Registration packet.
     Defaults to emulating the command-line growlnotify utility."""

  def __init__(self, application="NetGrowl", password = None ):
    self.notifications = []
    self.defaults = [] # array of indexes into notifications
    self.application = application.encode("utf-8")
    self.password = password
  # end def

  def addNotification(self, notification="Command-Line Growl Notification", enabled=True):
    """Adds a notification type and sets whether it is enabled on the GUI"""
    if enabled:
  # end def

  def payload(self):
    """Returns the packet payload.""" = struct.pack( "!BBH",
                             len(self.application) ) += struct.pack( "BB",
                              len(self.defaults) ) += self.application
    for notification in self.notifications:
      encoded = notification.encode("utf-8") += struct.pack("!H", len(encoded)) += encoded
    for default in self.defaults: += struct.pack("B", default)
    self.checksum = md5_constructor()
    if self.password:
       self.checksum.update(self.password) += self.checksum.digest()
  # end def
# end class

class GrowlNotificationPacket:
  """Builds a Growl Network Notification packet.
     Defaults to emulating the command-line growlnotify utility."""

  def __init__(self, application="NetGrowl",
               notification="Command-Line Growl Notification", title="Title",
               description="Description", priority = 0, sticky = False, password = None ):

    self.application  = application.encode("utf-8")
    self.notification = notification.encode("utf-8")
    self.title        = title.encode("utf-8")
    self.description  = description.encode("utf-8")
    flags = (priority & 0x07) * 2
    if priority < 0:
      flags |= 0x08
    if sticky:
      flags = flags | 0x0100 = struct.pack( "!BBHHHHH",
                             len(self.application) ) += self.notification += self.title += self.description += self.application
    self.checksum = md5_constructor()
    if password:
       self.checksum.update(password) += self.checksum.digest()
  # end def

  def payload(self):
    """Returns the packet payload."""
  # end def
# end class

if __name__ == '__main__':

    # send command line arguments to main() function

Super simple BASH script to monitor a process

Here’s a little BASH script that I made to monitor a virtual machine on an OS X box. Basically when its CPU usage gets higher than 75%, I get a Growl notification and a spoken warning from Bruce – one of the many Mac voices.

One thing to note:

ps -eo %cpu 207 | tail -1

is where the magic is done. Replace ‘207’ with the PID of whatever you want to monitor. It would be wiser to make this script monitor the process by name, but in my case I have the VM running all the time.


# CPU threshold
readonly THRESHOLD=75

while true; do
    # make the output of our command a variable
    set `ps -eo %cpu 207 | tail -1`
    # turn float into int by truncating from decimal after
    # if our CPU usage is above our threshold
    if [ "$toInt" -gt "$THRESHOLD" ]; then	
        # if we haven't displayed a Growl notification for this alarm
        if [ "$alarmState" -eq "0" ]; then	
            # display a Growl notification
            growlnotify -sm "`date` Warning! CPU is at $toInt!"
        # shout out our warning
        say -v Bruce "Warning! CPU is at $toInt!"
        # consider putting 'sleep' here
        # CPU usage is below our threshold
    # pause the script for a second
    sleep 1

Send preset messages automatically with Adium and AppleScript

After coming across this article today on Reddit, I decided to cook up a little AppleScript to accomplish the same task for us Mac users.

Disclaimer: I would never do this to my boss, so if any potential employers are out there scoping out my blog please know that it’s truly for entertainment purposes…

OK so here’s the script.

  • It will send all of the messages in a text file to whatever screen name you choose at defined or random intervals
  • Adium needs to be loaded and you need to be signed in
  • You need to create the text file and know its path. It expects the file to be in plain text and each message to be separated by a new line. I haven’t experimented with anything other than plain text and you could possibly have encoding issues and send some offensive message in Chinese.

Select all of the text below and copy it. Though it’s cut off on the sides it will still grab it all.

-- your Adium IM account name

-- screen name of target

-- path of input file with messages separated by a newline
-- example: "/Users/JohnDoe/Desktop/messages.txt"
set filePath to "PATHTOFILEHERE"

-- set minimum amount of time to wait before sending messages in seconds
set lowerTime to 200
-- set maximum amount of time to wait before sending messages in seconds
set upperTime to 800

-- open file for input and set variable for text
set textFile to (open for access (POSIX file filePath))
set textInput to (read textFile for (get eof textFile))
close access textFile

-- make a list of messages from every new line in the text file
set messages to every paragraph of textInput

-- make our counter variable the number of how many messages we have
set counter to count messages

-- send messages to our target at different intervals until we're out
repeat with counter from 1 to counter
	-- add a little bit of randomness to the delay
	delay (random number from lowerTime to upperTime)
	-- tell Adium to send the current message to our target
	tell application "Adium"
		-- set our current message to whatever message we're at
		set currentmessage to item counter of messages
		-- start a new chat with the target
		tell account imAccnt to set savedChat to make new chat with contacts {contact targetName} with new chat window
		send savedChat message currentmessage
	end tell
end repeat