はじめに
仕事でいろんなサーバにSSHするのだけれど(鳥脳のせいで)ドメインとかIP覚えきれないし、いちいちターミナル分割していくつも手動でログインするのもめんどくさいなぁと思っていたので、AppleScriptとPeco1で作ってみました。
やったこと
AppleScript書く
初めて書いたので多少戸惑ったけどこんな仕上がりに。
on run argv
set num_hosts to count of argv
if num_hosts = 0 then
return
end if
launch application "iTerm"
tell application "iTerm"
activate current terminal
tell the current terminal
launch session "Default Session"
tell the the current session
set current_host to 1
repeat with host in argv
if current_host > 1 then
if current_host < 6 then
tell i term application "System Events" to keystroke "d" using command down
else
tell i term application "System Events" to keystroke "]" using command down
tell i term application "System Events" to keystroke "D" using {command down, shift down}
end if
end if
delay 0.2
write text "ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null toremo@" & host
set current_host to current_host + 1
end repeat
end tell
end tell
end tell
end run
引数にアクセスしたいSSHのドメインなりIPなりを渡すとiTerm上に新しいタブを作ってhostの数だけPane分割しながらSSHアクセスします(ここでは横に作るPane数を5つ固定にしてます)。
Hostのリストを作る
Pecoに食わすHostの一覧を用意しました(1行1Host)。
web001
web002
proxy001
proxy002
db001
...
Shell書く
host一覧をPecoに食わせて、その戻りを配列化したものを引数にしてAppleScriptに渡すだけの簡単なShellを書きました。
#!/bin/bash
IFS=$'\n'
list=("$( peco ~/host_list.txt )")
osascript ~/multi_ssh.scpt $list
Aliasに起動コマンドを設定
最後にAliasに起動コマンドを設定して終了です。
alias mssh=". ~/multi_ssh_peco.sh"
これでターミナルからmssh
と叩いてやるだけで、Host一覧からPecoで選択したHostだけを一括SSHさせることができました。
所感
AppleScriptの記号の少なさに戸惑いながらも割とサクッとできました。
もう少しいろいろ工夫すればもっと柔軟にできそう。
一覧のHostが多くても、Pecoはインクリメンタルサーチで絞り込めるので"web"とか"db"とかで絞れば簡単に目的のサーバ見つけられるし、とてもイイ感じです。
Peco素敵!
参考にさせて頂いたサイト
https://github.com/peco/peco
http://mc909j.blogspot.jp/p/document.html
https://wimdeblauwe.wordpress.com/2014/07/16/opening-multiple-ssh-sessions-with-iterm-automatically/