SSH免密登陆

#!/bin/bash
#变量
username=$1
hostname=$2
password=$3

# 1. 生成密钥
if [ -f /root/.ssh/id_rsa ] || [ -f /root/.ssh/id_rsa.pub ];then
    echo "当地存在密钥对,现在进行清理并重新生成"
    rm -rf /root/.ssh/id_rsa /root/.ssh/id_rsa.pub &>/dev/null && echo "清理成功"
    sleep 3
fi

echo "生成密钥对...."
expect <<-EOF
    spawn ssh-keygen
    expect "(/root/.ssh/id_rsa):"
    send "\r"
    expect "(empty for no passphrase):"
    send "\r"
    expect "again:"
    send "\r"
    expect eof;
    EOF


# 2. 部署公钥(输入一次密码)

expect <<EOF
spawn ssh-copy-id ${username}@${hostname}
expect {
"*(yes/no)*" {send "yes\r";exp_continue}
"password" {send "$password\r"}
}
spawn ssh $username@$hostname
sleep 3
expect "*]#"
send "ip addr show\r"
expect "*]#"
send "exit\r"
expect eof;
EOF
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值