ssh 免交互搭建免密登陆环境脚本

#!/bin/bash

#ChengRuoFei

#sshAuto.sh脚本名,需要传入 对方服务器 用户和密码($1 $2 传参)

sshIP=$1
sshPassword=$2

#本机公私秘钥 expect免交互方式生成函数
function sshKeygenAuto() {
    if [ ! -e ~/.ssh/id_rsa.pub ]; then
        echo "The public/private rsa key pair not exist, start Generating..."
        yum install expect -y >/dev/null 2>&1
        expect -c "
            spawn ssh-keygen
            expect {
                \"ssh/id_rsa):\" {send \"\r\";exp_continue}
                \"passphrase):\" {send \"\r\";exp_continue}
                \"again:\" {send \"\r\";exp_continue}
            }
        " >/dev/null 2>&1
        if [ -e ~/.ssh/id_rsa.pub ]; then
            echo "Generating public/private rsa key pair successfully."
        else
            echo "Generating public/private rsa key pair failure!"
            
        fi
    fi
}

#发送对方服务器公钥匙的expect免交互函数

function sshCopyIdAuto() {
        cd
        expect -c "
                    spawn ssh-copy-id -i .ssh/id_rsa.pub $sshIP
            expect {
                \"(yes/no)?\" {send \"yes\r\";exp_continue}
                \"password:\" {send \"$sshPassword\r\";exp_continue}
            }
        " >/dev/null 2>&1
}

#对传参的判断并执行函数
[[  -z "$sshIP" ]] && echo "\$1   empty,please input   \$1 "  ! || sshKeygenAuto
[[  -z "$sshPassword" ]] && echo "\$2  empty,please input   \$2"  ! ||sshCopyIdAuto

#脚本到此完

###########################################################

#脚本执行过程:

 #测试环境为4台服务器,密码123456,具体执行命令如下:

vi sshAuto.sh 

bash sshAuto.sh 192.168.18.101 123456
bash sshAuto.sh 192.168.18.102 123456
bash sshAuto.sh 192.168.18.103 123456
bash sshAuto.sh 192.168.18.104 123456
scp sshAuto.sh  192.168.18.102:~
ssh 192.168.18.102 "bash sshAuto.sh 192.168.18.101 123456"
ssh 192.168.18.102 "bash sshAuto.sh 192.168.18.102 123456"
ssh 192.168.18.102 "bash sshAuto.sh 192.168.18.103 123456"
ssh 192.168.18.102 "bash sshAuto.sh 192.168.18.104 123456"
scp sshAuto.sh  192.168.18.103:~
ssh 192.168.18.103 "bash sshAuto.sh 192.168.18.101 123456"
ssh 192.168.18.103 "bash sshAuto.sh 192.168.18.102 123456"
ssh 192.168.18.103 "bash sshAuto.sh 192.168.18.103 123456"
ssh 192.168.18.103 "bash sshAuto.sh 192.168.18.104 123456"
scp sshAuto.sh  192.168.18.104:~
ssh 192.168.18.104 "bash sshAuto.sh 192.168.18.101 123456"
ssh 192.168.18.104 "bash sshAuto.sh 192.168.18.102 123456"
ssh 192.168.18.104 "bash sshAuto.sh 192.168.18.103 123456"
ssh 192.168.18.104 "bash sshAuto.sh 192.168.18.104 123456"
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

ChengRuoFei

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

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

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

打赏作者

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

抵扣说明:

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

余额充值