› Reconnecting iTerm ssh Sessions on Wake
If you spend lots of time connected to various remote systems via ssh then putting your computer to sleep can be quite annoying. Once you wake it back up, you have to go to each iTerm tab that contains a remote ssh session and close it (or wait for it to eventually time-out) then open a new one. The following script, run via SleepWatcher, will do this for you each time you wake your Mac from sleep.
› Installing SleepWatcher
Grab the SleepWatcher package from http://www.bernhard-baehr.de/. The current version (2.0.4) has two packages in the DMG. "sleepwatcher" and "SleepWatcher StartupItem" install both in this order. The second sets SleepWatcher to launch on boot and sets it up to look for a file named .wakeup and .sleep in the user's home directory on wake and sleep.
› The ~/.wakeup Script
#!/bin/bash
TARGET_SESSION=orion
counter=0
limit=20
DISCON=$(cat << EOC
tell application "iTerm"
activate
set TerminalList to terminals
repeat with myTerminal in TerminalList
set SessionList to sessions of myTerminal
repeat with mySession in SessionList
tell mySession
if name = "$TARGET_SESSION" then
terminate
end if
end tell
end repeat
end repeat
end tell
EOC);
RECON=$(cat << EOC
tell application "iTerm"
tell the first terminal
launch session "$TARGET_SESSION"
tell the last session
write text "screen -xd"
end tell
end tell
end tell
EOC);
echo "$DISCON" | osascript -
while [ "$counter" -lt "$limit" ]
do
curl http://www.google.com/ &> /dev/null
if [[ $? = 0 ]]; then
echo "$RECON" | osascript -
exit
fi
count=$(($count+1))
sleep 0.5
done
This script will close the specified TARGET_SESSION in iTerm then attempt to retrieve http://www.google.com/, if successful it will re-launch the TARGET_SESSION. If it fails, it will wait half a second and try again, up to 20 times (about 10 seconds) before relaunching the session. Somewhere between 1 and 3 seconds was usually the length of time it took my MacBook to reconnect to my WPA2 WIFI network.
Save this script as ".wakeup" in your home directory so that SleepWatcher will find it. Once saved, simply set the script to executable "chmod 700 ~/.wakeup" from a shell prompt and you are all set.
Thanks to Dan Christensen and Donnie Berkholz for helping me make AppleScript and bash come together in perfect harmony, despite my piddly small knowledge of bash scripting and Seemant Kulleen for pointing out some typos.

