iTerm and applescript

At Netlog (the company I work for) we have thousands of servers. Fortunately, every server has a logical name (eg.: web001, web002, web003, …).

From time to time, some monkeywork has to be done on a bunch of those servers. Although we have very nice tools for this, sometimes you just have to logon the box and type some commands manually. iTerm, my favourite terminal program on OSX, has a nice feature for doing this: “Send input to all tabs”. The hardest part is to open a new window with all the tabs and ssh’ing to the servers themselves. Once you have an ssh session in every tab you enable to send the input to all tabs and you’re done :)

Suppose:

You have 10 hosts: host01, host02, …, host10 and you want to execute the command ‘df -h’ (view the disk usage).
What you can do is open iTerm, create 10 tabs (press ‘command-t’ 10 times) and type in each tab: ’ssh host0x’ where x is the box you want to connect to.
Once you’re connected to each box, simply press ‘command-shift-i’ or choose “Send input to all tabs” and pick your favourite host.
Execute your command and when you browse through all the tabs, you’ll see the info of each server. Nice isn’t it? :)

“Hey, this is stupid, why are you blogging about this?”

Well, the annoying part is the establishing of the ssh connection itself. I really got sick of it and I was thinking if I could get the tab ID, I could do something like ’ssh host${TABID} ‘, send this to all my tabs and got logged in automatically. I wrote a very small applescript to do this.

tell application "iTerm"
	activate
	set format to "" & (choose from list {"0", "00", "000"} with prompt "Choose the format")
	set num to text returned of (display dialog "Enter the offset (default: 1)" default answer "1")
	-- Get the current terminal
	set myTerminal to current terminal
	-- Make a list of all the sessions (tabs) in this terminal (window) to iterate over
	set SessionList to sessions of myTerminal
	repeat with mySession in SessionList
		tell mySession
			set formatText to text -(count format) thru -1 of (format & num)
			write text "" & formatText
		end tell
		set num to num + 1
	end repeat
end tell

I was really amazed by the ease of applescript. It took me 20 minutes to write and debug this (being completely new to applescript).
The biggest help for me was the MacScripter site and in particular the posts of Craig Smith.

Although the chance that this snippet is useful for anybody except me is small, it’s a nice way to demonstrate how easy it is to automate something with applescript.

Cheers,
Nicolas

Leave a Reply

*
To prove that you're not a bot, enter this code
Anti-Spam Image