複数のマシンにsshして、同様の設定を行いたい。
そういう時に使いましょう。
スクリプト
以下zshのスクリプトです:
tmux-sync_ssh
#!/bin/zsh
tmux-sync_ssh() {
hosts=${(Z+n+)$(cat -)}
for host in $hosts[2,-1]; do
tmux splitw -p $(( 100 / (${#hosts} - 1))) ssh $host
done
tmux select-layout main-vertical
tmux set synchronize-panes on
ssh $hosts[1] <> /dev/tty
tmux set synchronize-panes off
}
tmux-sync_ssh $@
fzfと組み合わせる
ssh先を表示してくれる fzf-sshを用意して
以下のように繋げると便利です。
$ fzf-ssh -m --bind ctrl-a:toggle-all | tmux-sync_ssh
fzf-sshは以下のような感じで用意しておきます:
fzf-ssh
fzf_ssh(){
FZF_OPTS=${(z)@}
cat <(cat ~/.ssh/config /etc/ssh/ssh_config 0> /dev/null | \grep -i '^host' | tr ' ' '\n' | awk 'tolower($1) !~/^host/{print "host",$1}' | \grep -v '*') \
<(\grep -v '^\s*#' /etc/hosts | \grep -Fv '0.0.0.0') \
| awk '{if (length($2) > 0) {print $2}}' | sort -u | fzf $FZF_OPTS
}
fzf_ssh $@
解説
同時に複数のペインを操作する
$ tmux set synchronize-panes on
を使います。
これにより複数のペインに対して同じ操作を行うことができます。
レイアウトを整える
tmux select-layout main-vertical
複数のペインを開いたあとにこの行で
これはお好みで。
僕はひとつ大きいペインがあると操作しやすいので、このレイアウトにしています。
man tmuxから次のレイアウトが有効です
The following layouts are supported:
even-horizontal
Panes are spread out evenly from left to right across the window.
even-vertical
Panes are spread evenly from top to bottom.
main-horizontal
A large (main) pane is shown at the top of the window and the remaining panes are spread from left to right in the leftover space at the bottom. Use the main-pane-height window option to specify the height of the top pane.
main-vertical
Similar to main-horizontal but the large pane is placed on the left and the others spread from top to bottom along the right. See the main-pane-width window option.
tiled Panes are spread out as evenly as possible over the window in both rows and columns.
コマンドライン上のプロセスにターミナルを割り当てる
コマンドライン上のプロセスには標準入力などのptsが割り当てられないことから
ssh -tt
などして割り当てても、接続先をうまく操作できません。
これを解決するために
$ ssh $hosts[1] <> /dev/tty
を行なっています。
これは
$ ssh $hosts[1] < /dev/tty > /dev/tty
と等価です。
/dev/tty
が 現在のシェルのttyを表す特別なファイルになります。