LoginSignup
4
5

More than 5 years have passed since last update.

iTerm2(AppleScript)&pecoでイイ感じにSSHしてみる

Last updated at Posted at 2015-03-19

はじめに

仕事でいろんなサーバにSSHするのだけれど(鳥脳のせいで)ドメインとかIP覚えきれないし、いちいちターミナル分割していくつも手動でログインするのもめんどくさいなぁと思っていたので、AppleScriptとPeco1で作ってみました。

やったこと

AppleScript書く

初めて書いたので多少戸惑ったけどこんな仕上がりに。

multi_ssh.scpt
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)。

host_list.txt
web001
web002
proxy001
proxy002
db001
...

Shell書く

host一覧をPecoに食わせて、その戻りを配列化したものを引数にしてAppleScriptに渡すだけの簡単なShellを書きました。

multi_ssh_peco.sh
#!/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/


  1. percolをgo言語で書き換えたようなやつ。むちゃ便利。 

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5