Shell_expect实现自动交互免密登录操作

auto_keygen (){
    /usr/bin/expect<<EOF
    # 设置超时时间,单位为  秒
    set timeout 30

    # 触发交互命令
    spawn   ssh-keygen

    # 开始捕获
    expect {

        # 当捕获到此次字符串时, 发送回车,并且继续捕获
        ".ssh/id_rsa)" { send "\n"; exp_continue }
        "no passphrase):" { send "\n"; exp_continue}
        "again:" { send "\n"; exp_continue }
    }

EOF
}


send_key () {
/usr/bin/expect <<EOF
set timeout 30

# 继续发送第二条命令
spawn ssh-copy-id root@$1
expect {
"yes/no" { send "yes\n"; exp_continue }
"password:" { send "upsa\n"} }
expect eof
EOF
}

pub_key_file=$HOME/.ssh/id_rsa.pub

if [ ! -f ${pub_key_file} ];then
    auto_keygen
fi

for ip in $(cat ./ips.txt)
do
   send_key $ip
done
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容