- expect实现无交互登录
#!/usr/bin/expect定义脚本执行的shell
set timeout 30 设置超时时间,单位秒, timeout -1 永不超时
spawn expect内部命令,给ssh进程加壳,用来传递交互指令。(启动新的进程)
expect expect 内部命令,判断输出结果是否包含某项字符串,没有则立即返回,继续向下执行,有就等待一段时间返回,等待时间由timeout设置(从进程接收字符串)
send 执行交互动作,将交互要执行的动作进行输入给交互指令,命令结尾字符串要加上\r,如果出现异常等待的状态可以进行核查。(向进程发送字符串)
exp_continue 继续执行接下来的交互动作
interact 执行完成后保持交互状态,把控制权交给控制台;(允许用户交互)
$argv expect脚本可以接收从bash传递来的参数,可用[lindex $argv n ]获得,n从0开始,分别表示第一个,第二个,第三个...参数,
例1:免密码登通过ssh服务器,非密钥
vim ssh.exp
#!/usr/bin/expect
#timeout默认为10,expect空格{
set ip "192.168.0.60"
set name "root"
set passwd "123456"
set timeout 30
spawn ssh $name@$ip
expect {
"yes/no" {send "yes\r";exp_continue}
"password" {send "$passwd\r";}
}
expect "#"
send "touch /root/expect.txt\r"
send "ls /etc/ > /root/expect.txt\r"
send "exit\r"
expect eof
例2:对服务器批量管理
vim ip_pass.txt
192.168.0.60 123456
192.168.0.60 123456
<