Applescript to Interact with iTerm2
iTerm2 has decent support for Applescript. You can work with sessions, profiles, tabs, and more through Applescript. I only have one example, but it’s something I use in the real-world, so maybe it’ll help someone else.
The following script will open a new tab for every server in the list, and execute a command on that server. Let’s say a new version of Drush is available. I’d use this script to log into every server (we have no less than 15 servers) and check which version of Drush the server is running. I could then quickly update if needed, and I’m already logged in to do so.
The “servers” are defined in my
~/.ssh/config and use key-based authentication.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
tell application "iTerm" activate # Some servers as defined in ~/.ssh/config # Please test changes to this script with just a few servers! set servers to {"web242", "web122"} make new terminal repeat with server in servers tell the current terminal activate current session launch session "Default Session" tell the last session # Log into the server write text "ssh " & server # Optional (and lame approach); wait for connection (works regardless) delay 5 # Execute a command write text "drush --version" end tell end tell end repeat end tell |
This a pretty simple example. To take it one step further it’d be cool to cd into the drush directory, wherever that is on each server, before checking the drush version. Here’s something I’ve been getting help with (thanks to #bash on freenode; sorry if I’ve butchered this, which is why I’m not giving the nick of the person who helped me). Don’t forget to deal with single vs double quotes.
1 |
bin=$(type -p drush) && readlink "$bin" && bin=$(readlink "$bin") && cd "${bin%/*}"; drush --version |