Linux 批量配置互信

批量配置SSH互信脚本

bash 复制代码
#!/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 ]]; then
    username=$default_username
fi

if [[ -z $password ]]; then
    password=$default_password
fi


if command -v sshpass &> /dev/null
then
	echo "sshpass command is available"
else
	echo "sshpass command is not available"
	##### yum install 
	if [ -x /usr/bin/yum ]; then
		echo "Try to execute yum install.."
		yum -y install sshpass
	else
		echo "ERROR: An exception occurred during the installation of sshpass ! "
		exit -1
	fi
fi


function 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" ]; then
		mkdir -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"
	else
		echo "SSH key pair already exists: $private_key and $public_key"
	fi
}



# 循环遍历目标机器列表,判断主机是否有密钥
for machine in "${machines[@]}"
do
    echo "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[@]}"
do
    echo "Get the public key file in $machine to authorized keys"
    # sshpass -p "$password" ssh-copy-id -o StrictHostKeyChecking=no $username@$machine
	sshpass -p "$password" ssh -o StrictHostKeyChecking=no $username@$machine "cat ~/.ssh/id_rsa.pub " >> /tmp/authorized_keys
done

# 下发认证文件
for machine in "${machines[@]}"
do
    echo "Configuring passwordless access for $machine"
	sshpass -p "$password" scp -o StrictHostKeyChecking=no /tmp/authorized_keys $username@$machine:$HOME/.ssh
done

if [ $? == 0 ]
then
	echo "Passwordless access configured successfully for all machines."
	rm -f /tmp/authorized_keys
fi
相关推荐
ayaya_mana20 小时前
VS Code 远程开发:SSH连接与远程资源管理器的配置
linux·ide·windows·vscode·远程资源管理
l1t20 小时前
DeepSeek辅助编写的利用位掩码填充唯一候选数方法求解数独SQL
数据库·sql·算法·postgresql
choumin20 小时前
在 Debian 上安装并运行 PoCL
linux·编译·安装·pocl
墨月白20 小时前
[QT] QT中的折线图和散点图
数据库·qt
龙潜月七20 小时前
做一个背单词的脚本
数据库·windows·c#·aigc·程序那些事
我科绝伦(Huanhuan Zhou)20 小时前
DM数据库物理存储结构深度解析与理论实践
数据库·oracle
霖霖总总20 小时前
[小技巧23]全面理解 MySQL 的 WAL 机制:原理、影响与可观测性
数据库·mysql
列御寇20 小时前
MongoDB分片集概述
数据库·mongodb
又是忙碌的一天21 小时前
SpringMVC响应
java·服务器·数据库
Shanxun Liao21 小时前
CentOS 7.9 根分区 / 已经 100% 用满隐藏占用解决办法
linux·运维·centos