批量免密脚本

本文介绍了如何通过bash脚本批量为多台主机设置SSH免密登录,包括检查密钥生成、安装expect工具、创建和复制密钥,以及处理密码过期。重点在于使用`ssh-copy-id`命令实现无交互的远程登录配置。
摘要由CSDN通过智能技术生成

前提:

1. 保证需要做免密的机器网络互通,ssh端口防火墙彼此开放

2. 准备文件ip ,将需要做免密的主机ip和端口密码写入文件中并以【冒号】分割

ip:密码:端口

vim  ssh.sh

#!/bin/bash
hostname="root"

pub=~/.ssh/id_rsa.pub
#检查是否生成密钥
function key
{
        expect <<EOF
        spawn ssh-keygen
        expect {
        "/root/.ssh/id_rsa" { send "\n";exp_continue; }
        "Enter passphrase" { send "\n";exp_continue;}
        "again:" { send "\n";}
        };
        expect "fingerprint is:" {send "\n"} expect eof
EOF
}
#检查是否安装免交互命令
function exp
{
        which expect
        if [ $? == 0 ];then
                echo "expect 已存在!"

        else
                echo "expect 不存在,正在安装..."
                yum -y install expect
                $expe
                if [ $? == 0 ];then
                        echo "expect 已成功安装"
                else
                        echo "expect 安装失败"
                fi
        fi
}
#做免密
function sshkey
{
        expect <<EOF
        spawn ssh-copy-id -p $3  $hostname@$1
        expect {
        "yes/no" { send "yes\n";exp_continue; }
        "password" { send "$2\n";exp_continue;}
        };
        expect "]\#" {send "exit\n"} expect eof
EOF
}
#检查密码是否过期如果密码过期则修改密码
function ssh
{
        expect <<EOF
        spawn ssh -p $1  $hostname@$3
        expect {
        "(current) UNIX password:" { send "${oldpw}\n";exp_continue; }
        "New password:" { send "$2\n";exp_continue;}
        "Retype new password:" { send "$2\n";exp_continue;}
        };
        expect "]\#" {send "exit\n"} expect eof
EOF
}
exp
#监测密钥是否存在不存在则直接创建密钥
if [[ ! -f $pub ]];then
        echo "密钥不存在,正在重新创建密钥..."
        rm -rf ~/.ssh
        key
        [[ -f $pub ]]&& echo "密钥成功创建!!"
else
        echo "密钥已存在!"
fi
#读取主机文件并做远程免密
while read line
do
        for hosts in `echo ${line}`
        do
                for i in `echo "$hosts"`
                do
                        host=`echo $i|awk -F: '{print $1}'`
                        pw=`echo $i|awk -F: '{print $2}'`
                        port=`echo $i|awk -F: '{print $3}'`
                        ssh ${port} ${pw} ${host}
                        sshkey  ${host} ${pw} ${port}
                done
        done
done < ip

执行方法:

chmod  +x ssh.sh 

sh ssh.sh

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值