更新ssh key的脚本,供参考
#!/bin/bash
#install ssh-key to the host
hostno=$1
passwd=xxxxx
indicate_msg(){
msg=$1
echo ">>>>>>>>>>>>>>>>>>"${msg}
}
#clean the old StrictHostKey of hostno in /root/.ssh/known_hots
clean_StrictHostKey(){
indicate_msg ${FUNCNAME[@]}
ssh-keygen -R ${hostno}
}
#add the old StrictHostKey of hostno in /root/.ssh/known_hots
add_StrictHostKey(){
indicate_msg ${FUNCNAME[@]}
/usr/bin/expect << EOF
set timeout 1
spawn ssh-copy-id root@${hostno}
expect "*(yes/no)*"
send "yes\r"
expect eof
exit
wait
EOF
echo
}
#check if public key have added to the hostno
check_ssh_key(){
indicate_msg ${FUNCNAME[@]}
ssh ${hostno} -o PreferredAuthentications=publickey date
#ssh ${hostno} -o PreferredAuthentications=publickey date > /dev/null 2>&1
if [ $? = 0 ];then
echo "ssh-key to ${hostno} already added"
else
echo "ssh-key to ${hostno} not added"
return 1
fi
}
#add public key have added to the hostno
add_ssh_key(){
indicate_msg ${FUNCNAME[@]}
/usr/bin/expect << EOF
set timeout 1
spawn ssh-copy-id root@${hostno}
expect "*password*"
send "${passwd}\r"
expect eof
exit
wait
EOF
}
补充知识:
1. ssh
1.1 -o PreferredAuthentications=publickey 使用publickey进行登陆
1.2 -o StrictHostKeyChecking=no 不检查known_hosts里的公钥是不是可用
2. echo ${FUNCNAME[@]} 显示所在函数名
echo ${FUNCNAME[@]}
3. echo -e '\n' 显示回车需要用-e来解析,不用双引号
4. expect 中exit是退出当前进程(可能是子进程),wait等待主进程给子进程手尸
相关引用:
进程退出: https://blog.csdn.net/a970973835/article/details/48290059