Centos7下批量SSH免密登录服务器

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
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Vchaoren-1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值