利用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}
}
上一篇:Linux 自动化执行命令


下一篇:node: 使用res.send()时报错RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code:18