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
相关推荐
Dlwyz8 分钟前
问题: redis-高并发场景下如何保证缓存数据与数据库的最终一致性
数据库·redis·缓存
编程修仙24 分钟前
Collections工具类
linux·windows·python
芝麻团坚果40 分钟前
对subprocess启动的子进程使用VSCode python debugger
linux·ide·python·subprocess·vscode debugger
Elastic 中国社区官方博客1 小时前
Elasticsearch 中的热点以及如何使用 AutoOps 解决它们
大数据·运维·elasticsearch·搜索引擎·全文检索
写点什么啦1 小时前
[debug]不同的window连接ubuntu的vscode后无法正常加载kernel
linux·vscode·ubuntu·debug
wellnw1 小时前
[ubuntu]编译共享内存读取出现read.c:(.text+0x1a): undefined reference to `shm_open‘问题解决方案
linux·ubuntu
如意机反光镜裸1 小时前
如何快速将Excel数据导入到SQL Server数据库
数据库
不爱学习的YY酱1 小时前
【操作系统不挂科】<CPU调度(13)>选择题(带答案与解析)
java·linux·前端·算法·操作系统
DC_BLOG1 小时前
Linux-Nginx虚拟主机
linux·运维·nginx
坐公交也用券1 小时前
使用Python3实现Gitee码云自动化发布
运维·gitee·自动化