shell——expect

安装expect

rpm -qa expect    #查看是否安装
yum install expect -y

 

bash脚本使用expect自动应答

修改用户密码
#!/bin/bash
expect <<EOF &>/dev/null
spawn passwd $1    #产passwd命令
expect "rd:"    #当结尾停在rd:时
send "$2\r"    #把$2传给它
expect "rd:"
send "$2\r"
expect eof    #结束expect
EOF
expect实现ssh

#!/bin/bash
sed -i '/^'$1'/d' /root/.ssh/known_hosts
expect <<EOF &>/dev/null
spawn ssh $1
expect "no)?"
send "yes\r"
expect "password:"
send "$2\r"
expect "# "
send "touch /home/test\n"
send "exit\n"
expect eof
EOF

 

exp脚本

cat test.exp
#!/usr/bin/expect spawn passwd $1 #产passwd命令 expect "rd:" #当结尾停在rd:时 send "$2\r" #把$2传给它 expect "rd:" send "$2\r" expect eof #结束expect

执行脚本:expect test.exp

 

expect多次匹配

#!/usr/bin/expect
spawn passwd user
expect {
        "rd:"   {send "12345\r";exp_continue}
}
expect eof

 

脚本变量

#!/usr/bin/expect
set user [lindex $argv 0]  #把第一个参数赋值给变量user
set password [lindex $argv 1]  #把第二个参数赋值给password
spawn passwd $user
expect {
        "rd:"   {send "$password\r";exp_continue}
}
expect eof

执行:expect test.exp abc 12345

 

timeout

#!/usr/bin/expect
spawn ssh root@192.168.20.252 uptime set timeout 3 #设置超时时间3秒 expect "yes/no" send "yes/r" expect timeout send_user "timeout~" #终端打印 return #退出
#!/usr/bin/expect
spawn ssh root@192.168.20.252 uptime
expect {
    -timeout 3
    "yes/no"    {send "yes\r";exp_continue}
    timeout     {send_user "timeout~";return}
}

# -time 0 表示立即超时,-1 永不超时

 

posted @ 2016-11-15 17:44  沄持的学习记录  阅读(175)  评论(0)    收藏  举报