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
相关推荐
独行soc38 分钟前
#渗透测试#漏洞挖掘#红蓝攻防#护网#sql注入介绍08-基于时间延迟的SQL注入(Time-Based SQL Injection)
数据库·sql·安全·渗透测试·漏洞挖掘
White_Mountain1 小时前
在Ubuntu中配置mysql,并允许外部访问数据库
数据库·mysql·ubuntu
Code apprenticeship1 小时前
怎么利用Redis实现延时队列?
数据库·redis·缓存
百度智能云技术站1 小时前
广告投放系统成本降低 70%+,基于 Redis 容量型数据库 PegaDB 的方案设计和业务实践
数据库·redis·oracle
装不满的克莱因瓶1 小时前
【Redis经典面试题六】Redis的持久化机制是怎样的?
java·数据库·redis·持久化·aof·rdb
LIKEYYLL1 小时前
GNU Octave:特性、使用案例、工具箱、环境与界面
服务器·gnu
云云3212 小时前
搭建云手机平台的技术要求?
服务器·线性代数·安全·智能手机·矩阵
云云3212 小时前
云手机有哪些用途?云手机选择推荐
服务器·线性代数·安全·智能手机·矩阵
cominglately2 小时前
centos单机部署seata
linux·运维·centos
魏 无羡2 小时前
linux CentOS系统上卸载docker
linux·kubernetes·centos