Centos7下批量SSH免密登录
linux-Centos7下通过脚本实现批量实现免密登录。
环境
Centos7
作者编写环境:
CentOS Linux release 7.6.1810 (Core)
实现语言:
bash、expect
##环境准备
yum install expect
##文件说明
hosts----需要配置远程免密登录的服务器信息
create_keytoserver.sh----程序入口,实现的主程序
send_sshk.sh----实现远程登录的辅助脚本
1、hosts
格式说明:
cat hosts
10.10.1.2 22 root 123456
2、create_keytoserver.sh
脚本说明:
第一次构建需要打开注释,需要注意。
如果打开此注释,会删除以前的免密秘钥,请注意备份。
cat create_keytoserver.sh
#!/bin/sh
. /etc/init.d/functions
#判断参数个数是否符合要求
if [ $# -ne 1 ];then
echo "usage:$0 <hosts_file>"
exit 1
fi
time_temp=`date +"%Y_%m_%d_%H_%M"`
echo $time_temp >> run.log
#先删除秘钥,如果存在没有则会创建不成功
#rm -rf ~/.ssh/
#生成秘钥
#ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa >/dev/null 2>&1
#读取主机文件
while read line
do
#行字符不为空 才做校验
echo $line
if [ ! -z "$line" ];then
#分割字符串成数组
remoteHost=(${line// / })
#执行分发ssh key
echo "${remoteHost[0]} ${remoteHost[1]} ${remoteHost[2]} ${remoteHost[3]}"
sh send_sshk.sh ${remoteHost[0]} ${remoteHost[1]} ${remoteHost[2]} ${remoteHost[3]} ~/.ssh/id_rsa.pub
#>/dev/null 2>&1
if [ $? == 3 ];then
action "${remoteHost[0]} ssh-key to ${hostno} already added" /bin/true
echo "${remoteHost[0]} ssh-key to ${hostno} already added" >>run.log
continue
fi
ssh -p ${remoteHost[1]} ${remoteHost[0]} -o PreferredAuthentications=publickey -o ServerAliveInterval=10 date < /dev/null
res=$?
if [ $res == 0 ];then
action "${remoteHost[0]}" /bin/true
action "${remoteHost[0]}" /bin/true >>run.log
else
action "${remoteHost[0]}" /bin/false
action "${remoteHost[0]}" /bin/false >>run.log
fi
fi
done <$1
3、send_sshk.sh
```bash
cat send_sshk.sh
#!/usr/bin/expect
if [ $# != 5 ];then
echo "usage: $argv0 <remote_host> <remote_port> <remote_user> <remote_pwd> <id_dsa.pub_file>"
exit 1
fi
remote_host=$1
remote_port=$2
remote_user=$3
remote_pwd=$4
ssh_key_file=$5
if [ "`grep -c "${remote_host}" ~/.ssh/known_hosts`" -eq 1 ];then
ssh -p $remote_port $remote_user@$remote_host -o PreferredAuthentications=publickey -o ServerAliveInterval=10 date < /dev/null
if [ $? = 0 ];then
exit 3
fi
fi
/usr/bin/expect <<-EOF
set timeout 5
spawn ssh-copy-id -i ${ssh_key_file} -p ${remote_port} ${remote_user}@${remote_host}
expect {
"*yes/no*" {
send "yes\r"; exp_continue
}
"*assword:" {
send "$remote_pwd\n";exp_continue
send "exit\r"
}
eof {
exit
}
}
expect eof
EOF
4、使用方法
```bash
sh create_keytoserver.sh hosts