微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

利用expect在bash实现自动完成ssh互相配置

yum install expect -y
ls /usr/bin/expect

#!/bin/bash

if [ ! -d "/root/.ssh/" ]; then
    echo "/root/.ssh/ not exist, create rsa key"
    ssh-keygen -t rsa -N '' -f ~/.ssh/id_rsa
fi
if [ ! -f "/root/.ssh/id_rsa.pub" ]; then
    echo "/root/.ssh/id_rsa.pub not exist, create rsa key"
    ssh-keygen -t rsa -N '' -f ~/.ssh/id_rsa
fi

/usr/bin/expect <(cat << EOF
# add to kNown_hosts
spawn ssh-copy-id 192.168.180.123
expect {
    "*yes/no" {send "yes\r";exp_continue}
    "*new key" {send \x03}
}

# send key to remote
spawn ssh-copy-id 192.168.180.123
expect {
    "*password:" {send "111111\r";exp_continue}
}
EOF
)

可以先写expect脚本,打开调试看看匹配的关键词。expect -d ex.sh

#!/usr/bin/expect

# add to kNown_hosts
spawn ssh-copy-id 192.168.180.123
expect {
    "*yes/no" {send "yes\r";exp_continue}
    "*new key" {send \x03}
}

# send key to remote
spawn ssh-copy-id 192.168.180.123
expect {
    "*password:" {send "111111\r";exp_continue}
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐