使用tmux同时登录多个ssh服务器,并同步执行命令

tmux很方便运维人员使用,可以保持会话,会话共享和同时操作多个服务器

需求

希望能够同时操作多个服务器相同命令,多会话

版本1

网上有一个ssh-multi的版本 https://gist.github.com/dmytro/3984680 具体代码如下

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/bin/bash
# ssh-multi
# D.Kovalov
# Based on http://linuxpixies.blogspot.jp/2011/06/tmux-copy-mode-and-how-to-control.html

# a script to ssh multiple servers over multiple tmux panes


starttmux() {
    if [ -z "$HOSTS" ]; then
       echo -n "Please provide of list of hosts separated by spaces [ENTER]: "
       read HOSTS
    fi

    local hosts=( $HOSTS )


    tmux new-window "ssh ${hosts[0]}"
    unset hosts[0];
    for i in "${hosts[@]}"; do
        tmux split-window -h  "ssh $i"
        tmux select-layout tiled > /dev/null
    done
    tmux select-pane -t 0
    tmux set-window-option synchronize-panes on > /dev/null

}

HOSTS=${HOSTS:=$*}

starttmux

这个使用方法就是把host传在脚本后面,用法比较简单 ssh-multi xxx即可

版本2

希望能够支持自定义端口,定义用户,把需要操作的host放到文件里面,考这一版所以写了如下脚本

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#!/usr/bin/env bash
# usage: ssh-multi for tmux by liuliancao at 2021/04/22 v1.
# a script to ssh multiple servers over multiple tmux panes
while getopts p:u:f: OPTION
do
    case $OPTION in
        p)PORT=$OPTARG;;
        u)USER=$OPTARG;;
        f)FILE=$OPTARG;;
        ?)echo "use ssh-multi -p $PORT -u $USER -f ssh-hosts-file" && exit 1;;
    esac
done
index=-1

# split window to ssh
cat $FILE | while read host; do
    index=$(($index + 1))
    #if in tmux
    if [[ -z $TMUX ]];then
        in_tmux=0
        [[ $index -eq 0 ]] && tmux new-session  -d  "ssh -p $PORT $USER@$host" && continue
        tmux split-window -h  "ssh -p $PORT $USER@$host"
    # if not
    else
       in_tmux=1
       [[ $index -eq 0 ]] && tmux new-window  -n "ssh-multi" "ssh -p $PORT $USER@$host" && continue
       tmux split-window  -t "ssh-multi"  "ssh -p $PORT $USER@$host"
    fi
    tmux select-layout tiled
done

tmux set-window-option synchronize-panes on

[[ in_tmux -eq 0 ]] && tmux a