expect 是个不错的命令,可以完成一系列的自动化命令操作。对每次ssh登录输入密码这么麻烦的时候使用深有体会。多数固定的命令执行,也可以通过expect来操作执行,非常的方便。
如下例子,我们通过expect来完成一系列的操作有读取实时日志
#!/usr/bin/expect
spawn ssh [email protected]
set timeout 30
expect "password"
send "123456"
send "\n"
set timeout 5
expect “:~>”
send "sudo su -"
send "\n"
expect "~ #"
send "tail -200f /var/log/nginx/access.log"
send "\n"
interact
spawn是进入expect环境后才可以执行的expect内部命令,那么首先确定环境安装了expect。
expect我的理解有点类似if 的判断
send 是执行到某一步要输入的键位
interact 保证登录不退出,没有的话执行完成即退出
对于执行可能产生的延迟部分我用timeout来延迟执行命令