尋常でないもふもふ

a software engineer blog

iTermをAppleScriptで開くと便利

Web サービスを運用してると、頻繁にサーバへログインする必要がでてくる。特にエラーログを眺めたいときとか、本番環境の Web サーバ 4 台にアクセスするとき等、1回1回ログインするのは面倒。 そんな時は AppleScript で iTerm をまとめて開くスクリプトを書いとくと便利。

やり方

Mac OS X には標準で AppleScript エディタが入ってるので、それに下記スクリプトをコピペして実行。 あるいはスクリプトの保存時に「アプリケーション形式」で保存して実行する。

スクリプト

iTerm の1つのタブを4分割して4環境にログインするスクリプト

tell application "iTerm"
    activate
    
    tell current terminal
        set dev_web01 to "ssh jnst@dev-web-01.example.jp"
        set dev_web02 to "ssh jnst@dev-web-02.example.jp"
        set dev_web03 to "ssh jnst@dev-web-03.example.jp"
        set dev_web04 to "ssh jnst@dev-web-04.example.jp"
        
        launch session "dev-web" --ここの名前はなんでもいい
        
        tell the last session to write text dev_web01
        tell i term application "System Events" to keystroke "D" using command down
        tell the last session to write text dev_web02
        tell i term application "System Events" to keystroke "D" using command down
        tell the last session to write text dev_web03
        tell i term application "System Events" to keystroke "D" using command down
        tell the last session to write text dev_web04
    end tell
end tell

これは愚直に書き並べてるけど、host 名は 01〜04 みたいな形式でほぼ同一なので、repeat with のループ文を使い、文字列連結して書いた方がキレイ。

ウィンドウ分割の説明

垂直分割(Split Vertically)

tell i term application "System Events" to keystroke "D" using command down

iTerm では Command + D のショートカットキーで現在のセッションを新たに垂直分割して追加するので、それを利用してる

水平分割(Split Horizontally)

tell i term application "System Events" to keystroke "D" using {command down, shift down}

水平分割の場合は、Command + Shift + D のショートカットキー

本当はプロファイルを開きたい

上記はのやり方だと、単純に ssh でログインしているだけなので、バックグラウンドカラーなどはデフォルトのプロファイルと同一になってしまう。 本来なら本番環境は背景赤などにしたいので、プロファイル名を指定して分割したいが、現状はできないみたい。
新しいタブを開きたいだけなら、launch session "プロファイル名"で開くことはできる。水平分割したいときにプロファイル名指定ができない。