Through the expect command, ssh-key -t -rsa -b 2048 is automatically exempt from interaction.
Normal manual operations (assuming that there is no password, press enter, press y):
$ cat testExpect.sh
#!/usr/bin/expect
echo "test expect ....."
expect -c "
spawn ssh-keygen -t rsa -b 2048
expect {
\"Enter file in\" {send \"\r\"; exp_continue}
\"Overwrite\" {send \"y\r\"; exp_continue}
\"Enter passphrase\" {send \"\r\";exp_continue}
\"passphrase again\" {send \"\r exit\";exp_continue}
}
"
echo "end ....."
=split line===
Reference example:
# -c:执行脚本前先执行的命令,可多次使用。
expect -c "
#使用spawn进行 连接操作
spawn ssh -p $PORT $USER@$IP
expect {
#当碰到 yes/no的时候send发送 yes , \r表示回车键, 否则 exp_continue表继续执行
\"(yes/no)\" {send \"yes\r\"; exp_continue}
\"password:\" {send \"$PASS\r\"; exp_continue}
# 碰到 $USER@*时,这里的*是通配符。
\"$USER@*\" {send \"$COMMAND\r exit\r\"; exp_continue}
}
"
Reference blog: https://blog.csdn.net/zhandar44/article/details/91488287