simple tmux helper script to work simultaneously on many ssh sessions

I recently found a nice way to work on multiple servers using tmux and OpenSSH (not only, but who uses something else?). 

The script looks like this:

#!/bin/sh

if [ $# -gt 0 ]; then
  OK="0"
  for host in $(egrep '^host' ~/.ssh/config | grep -v '\*' | pcregrep -o "\s+$1\S*?(\s|$)")
  do
    OK="1"
    STYLE=$(pcregrep -A1 "\s$host(\s|$)" ~/.ssh/config | grep -o 'tmux-style: .*' | cut -d' ' -f2-)
    tmux send-keys "ssh $host $2" \; select-pane -P "$STYLE" \; split-window \; select-layout tiled
  done
  if [ $OK = "1" ]; then
    tmux set-window-option synchronize-panes \; send-keys ENTER
    tmux kill-pane \; select-layout tiled
  fi
fi

The script reads your ~/.ssh/config file and based on host entries it creates panes in a single tmux window and synchronises inputs to them. This allows for a simultaneous work done on multiple machines.

It also supports for setting styles for different hosts in your ~/.ssh/config file.



Usage:

Assuming you have a ~/.ssh/config file that looks like this:

host abc-*
  User root

host abc-prod
  # tmux-style: bg=red
  Hostname 192.168.0.1

host abc-dr
  # tmux-style: bg=blue
  Hostname 192.168.0.2

host def-vm-*
  User admin

host def-vm-1
  Hostname 192.168.0.11

host def-vm-2
  Hostname 192.168.0.12

host def-vm-3
  Hostname 192.168.0.13

host def-vm-4
  Hostname 192.168.0.14

host def-vm-5
  Hostname 192.168.0.15

And also assuming that you saved the script in ~/bin/st then running this command:

$ st abc

will spawn to synchronised panes in your current window one with red and one with blue background

if you run:

$ st def-vm 

or 

$ st def-

it will spawn five panes to each one of the def-vm machines.

No comments:

Post a Comment