前言: 下面使用expect实现自动化交互登录远程主机!
example code:
#!/usr/bin/expect
# spawn 引起的意思。表示建立/启动ssh会话
spawn ssh root@192.168.98.5
# 发送回车并接收字符串
expect {
# ps:send发送字符;"yes/no"与 "password:"表示匹配的字符;\r表示回车
"yes/no" { send "yes\r";exp_continue} # 键入yes
"password:" { send "111111\r" } # 键入密码
}
# ps: 这里的eof作为输入结束分界符!表示到这里expect就结束匹配!
expect eof
# ps:表示保持交互状态,因为默认是执行完上面的代码就会关闭交互也就是关闭session。
interact
# send:用于向进程发送字符串
# expect:发送回车然后匹配{}中的字符并作出动作!
# spawn:建立ssh会话
# interact:继续保持用户交互
# exp_continue 继续匹配的意思,因为匹配了"yes/no",下面还有一个password所以要继续让expect继续匹配!
# expect脚本的执行命令:expect expect_name.sh
run result: