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}
}