BASH 使用 sshpass 根据服务器列表向多个服务器发送相同的命令?

BASH with sshpass send same command to multiple servers based on list of servers?

您好,我有下面的“脚本”,它运行良好。

#!/bin/bash
TARGET="vm-windows-server01.local"
TARGET_USER="administrator"
TARGET_PASSWORD="Qwerty"

TARGET2="vm-linux-server01.local"
TARGET_USER2="root"
TARGET_PASSWORD2="Qwerty123"

#Windows server shutdown
sshpass -p $TARGET_PASSWORD ssh -o stricthostkeychecking=no $TARGET_USER@$TARGET 'shutdown /s /c "Shutting down"'

#Linux server shutdown
sshpass -p $TARGET_PASSWORD2 ssh -o stricthostkeychecking=no $TARGET_USER2@$TARGET2 'shutdown 3 "Shutting down"'

现在不再需要为 50 多台服务器复制 TARGET 变量以及 50 多行 sshpass 可以做下面这样的事情吗?请注意它的伪造代码只是为了让我知道我想要什么。我是 bash 的新手,所以要温柔 :-)

#!/bin/bash
WINDOWS_SERVERS="
     vm-windows-server01.local,
     vm-windows-server02.local,
     vm-windows-server03.local"

WINDOWS_USER="administrator"
WINDOWS_PASSWORD="Qwerty"

LINUX_SERVERS="
     vm-linux-server01.local,
     vm-linux-server02.local,
     vm-linux-server03.local"

LINUX_USER="root"
LINUX_PASSWORD="Qwerty123"

#Windows server shutdown
sshpass -p $WINDOWS_PASSWORD ssh -o stricthostkeychecking=no $WINDOWS_USER@$WINDOWS_SERVERS 'shutdown /s /c "Shutting down"'
    
#Linux server shutdown
sshpass -p $LINUX_PASSWORD ssh -o stricthostkeychecking=no $LINUX_USER@$LINUX_SERVERS 'shutdown 3 "Shutting down"'

基本上为列表中的所有主机运行 sshpass。

如果您不确定 Bash 或另一个了解数组的 shell 的可用性;您可以调整代码以使用 POSIX 可用语法(无数组)遍历服务器列表:

#!/usr/bin/env sh

WINDOWS_SERVERS="
     vm-windows-server01.local,
     vm-windows-server02.local,
     vm-windows-server03.local"

WINDOWS_USER="administrator"
WINDOWS_PASSWORD="Qwerty"

LINUX_SERVERS="
     vm-linux-server01.local,
     vm-linux-server02.local,
     vm-linux-server03.local"

LINUX_USER="root"
LINUX_PASSWORD="Qwerty123"

echo "$WINDOWS_SERVERS" | {
  IFS=$(printf '\t\n, ')
  while read -r windows_host || [ "$windows_host" ]
  do
    sshpass -p "$WINDOWS_PASSWORD" ssh -o stricthostkeychecking=no "$WINDOWS_USER@$windows_host" 'shutdown /s /c "Shutting down"'
  done
}

echo "$LINUX_SERVERS" | {
  IFS=$(printf '\t\n, ')
  while read -r linux_host || [ "$linux_host" ]
  do
    sshpass -p "$LINUX_PASSWORD" ssh -o stricthostkeychecking=no "$LINUX_USER@$linux_host" 'shutdown 3 "Shutting down"'
  done
}

但是如果你有bash、支持数组的zsh或ksh 93+,你的脚本语法更简单,更容易维护:

#!/usr/bin/env bash

WINDOWS_SERVERS=(
  'vm-windows-server01.local'
  'vm-windows-server02.local'
  'vm-windows-server03.local'
)

WINDOWS_USER='administrator'
WINDOWS_PASSWORD='Qwerty'

LINUX_SERVERS=(
  'vm-linux-server01.local'
  'vm-linux-server02.local'
  'vm-linux-server03.local'
)

LINUX_USER='root'
LINUX_PASSWORD='Qwerty123'

for windows_host in "${WINDOWS_SERVERS[@]}"
do
  sshpass -p "$WINDOWS_PASSWORD" ssh -o stricthostkeychecking=no "$WINDOWS_USER@$windows_host" 'shutdown /s /c "Shutting down"'
done

for linux_host in "${LINUX_SERVERS[@]}"
do
  sshpass -p "$LINUX_PASSWORD" ssh -o stricthostkeychecking=no "$LINUX_USER@$linux_host" 'shutdown 3 "Shutting down"'
done