批量配置SSH互信脚本
#!/bin/bash# 定义目标机器列表
machines=(
"192.168.122.87"
"192.168.122.89"
"192.168.122.90"
)
set -o errexit
# 设置默认的用户名和密码
default_username="root"
default_password="111111"# 读取目标机器的用户名和密码
read -p "Enter username [$default_username]: " username
read -s -p "Enter password [$default_password]: " password
echo# 使用默认值,如果没有输入用户名或密码
if [[ -z $username ]]; thenusername=$default_username
fiif [[ -z $password ]]; thenpassword=$default_password
fiif command -v sshpass &> /dev/null
thenecho "sshpass command is available"
elseecho "sshpass command is not available"##### yum install if [ -x /usr/bin/yum ]; thenecho "Try to execute yum install.."yum -y install sshpasselseecho "ERROR: An exception occurred during the installation of sshpass ! "exit -1fi
fifunction chk_ssh(){# ssh 公私钥路径ssh_dir="$HOME/.ssh"private_key="$ssh_dir/id_rsa"public_key="$ssh_dir/id_rsa.pub"# 检查~/.ssh目录是否存在if [ ! -d "$ssh_dir" ]; thenmkdir -p "$ssh_dir"fi# 检查是否存在私钥和公钥文件if [ ! -f "$private_key" ] || [ ! -f "$public_key" ]; then# 生成密钥文件ssh-keygen -t rsa -b 2048 -N "" -q -f "$private_key"echo "Generated new SSH key pair: $private_key and $public_key"elseecho "SSH key pair already exists: $private_key and $public_key"fi
}# 循环遍历目标机器列表,判断主机是否有密钥
for machine in "${machines[@]}"
doecho "Configuring passwordless access for $machine"sshpass -p "$password" ssh -o StrictHostKeyChecking=no $username@$machine "bash -s" << EOF
# 将本地函数chk_ssh传递给远程服务器
$(declare -f chk_ssh)
chk_ssh
EOF
done# 循环遍历目标机器列表,获取公钥
rm -f /tmp/authorized_keys
for machine in "${machines[@]}"
doecho "Get the public key file in $machine to authorized keys"# sshpass -p "$password" ssh-copy-id -o StrictHostKeyChecking=no $username@$machinesshpass -p "$password" ssh -o StrictHostKeyChecking=no $username@$machine "cat ~/.ssh/id_rsa.pub " >> /tmp/authorized_keys
done# 下发认证文件
for machine in "${machines[@]}"
doecho "Configuring passwordless access for $machine"sshpass -p "$password" scp -o StrictHostKeyChecking=no /tmp/authorized_keys $username@$machine:$HOME/.ssh
doneif [ $? == 0 ]
thenecho "Passwordless access configured successfully for all machines."rm -f /tmp/authorized_keys
fi