一、脚本说明
1、用法:./script.sh "user_name" "password_user" "password_root"
2、当互信的为非root用户时,先自动完成root的互信,然后检测指定用户是否存在,若不存在,则先创建,然后继续进行互信
3、缺点:
①所用服务器的所有互信用户,其所使用的rsa密钥,均为脚本所在服务器的root的rsa密钥
②需要所有服务器的root密码是一样的
二、脚本内容
#!/bin/bash
auth_user=$1
auth_passwd=$2
root_passwd=$3
#上面三个参数也可设置默认值,参考如下
#auth_user=${1:-postgres}
#auth_passwd=${2:-123456}
#root_passwd=${3:-123456}
array_node=(gtm gtm_standby node1 node2)
function rsa_create {
rm -rf ~/.ssh/*
/usr/bin/expect << EOF
spawn /usr/bin/ssh-keygen -t rsa
expect {
"*id_rsa):" {send "\n"; exp_continue}
"(y/n)?" {send "y\r"; exp_continue}
"passphrase" {send "\n"; exp_continue}
"again:" {send "\n"}
}
expect {
"*# " {send "exit\n\r"}
}
EOF
rsa_key=`cat ~/.ssh/id_rsa.pub | awk '{print $1,$2}'`
cat /dev/null > ~/.ssh/authorized_keys
for node in `echo ${array_node[@]}`
do
echo "${rsa_key} ${1}@${node}" >> ~/.ssh/authorized_keys
if [ "$1" != "root" ]; then
echo "${rsa_key} root@${node}" >> ~/.ssh/authorized_keys
fi;
done;
}
function rsa_scp {
for node in `echo ${array_node[@]}`
do
/usr/bin/expect << EOF
spawn /usr/bin/scp root@gtm :~/.ssh/* root@${node}:~/.ssh
expect {
"*yes/no*" {send "yes\r"; exp_continue}
expect {
"*assword*" {send "${root_passwd}\r"}
}
"*assword*" {send "${root_passwd}\r"}
}
expect "100%"
EOF
done;
}
rsa_create "${auth_user}"
case "${auth_user}" in
"root" )
rsa_scp
;;
* )
rsa_scp
for node in `echo ${array_node[@]}`
do
user_status=`ssh root@${node} -T "id ${auth_user} >/dev/null 2>&1 ;echo $?"`
if [ $user_status -ne 0 ]; then
ssh root@${node} -T "useradd ${auth_user} ; echo 123456 | passwd -f --stdin ${auth_passwd} > /dev/null 2>&1"
fi;
ssh root@${node} -T "/bin/cp -r -f /root/.ssh/* /home/${auth_user}/.ssh/;chown -R ${auth_user}:${auth_user} /home/${1}/"
done;
;;
esac
原文链接:https://blog.csdn.net/weixin_33852020/article/details/92081638