Linux-cluster集群节点互访免密脚本

Linux-cluster集群节点互访免密脚本

#! /bin/bash

# 自动获取IP列表,无需手动修改追加需要免密的hostIP
# 需要使用expect,若没有需要提前安装(联网或者本地配置yum源)


# 判断expect是否安装
expect -version
if [ $? -ne "0" ]
	then
	yum install -y expect
fi

sleep 10


# 获取需要免密的主机IP 手动追加输入
ip_List="158.220.130.201 158.220.130.202 158.220.130.203"
# 获取需要免密的主机IP 自动获取(/etc/hosts)
#ip_List=`grep -v 'localhost' /etc/hosts | awk -F ' ' '{print $1}'`

# 获取所有主机的密码
PASSWD="Kfcx@1234"

# 自定义函数
# 将公钥发送到其他节点包括当前节点
auto_ssh_copy_id(){
	expect -c "set timeout -1;
	spawn ssh-copy-id root@$1; # 可修改需要免密访问的用户名
	expect {
		*(yes/no)* {send -- yes\r;exp_continue;}
		*password* {send -- $2\r;exp_continue;}
		eof {exit 0;}
	}";
}

# 自定义函数
# 生成当前主机节点的公钥及私钥
create_ssh_id(){
	expect -c "set timeout -1;
	spawn ssh-keygen -t rsa;
	expect {
		*.ssh/id_rsa* {send -- \r;exp_continue;}
		*passphrase* {send -- \r;exp_continue;}
		*again:* {send -- \r;exp_continue;}
		eof {exit 0;}
	}";
}

# 自定义函数
# 循环获取每个主机IP 调用相应函数
ssh_copy_id_to_all(){

	for SERVER in $ip_List
	do
		auto_ssh_copy_id $SERVER $PASSWD
	done
}


# 调用生成私钥及公钥函数
create_ssh_id
# 调用发送公钥到其他节点函数
ssh_copy_id_to_all

注意事项:

  1. expect确认安装 也可以将代码中的安装步骤注释,手动安装expect以确保安装成功;
  2. 若自动获取IP列表注意ip与映射名之间的分隔符,awk是以空格分隔,确保分隔符正确;
  3. 脚本中是以root用户互访免密,若需要其他用户设置免密互访需修改用户名称;
posted @ 2022-01-04 14:23  余生&安好  阅读(61)  评论(0编辑  收藏  举报