Expect语法和应用

expect - programmed dialogue with interactive programs

Expect is a program that “talks” to other interactive programs according to a script. Following the script, Expect knows what can be expected from a program and what the correct response should be. An interpreted language provides branching and high-level control structures to direct the dialogue.

yum install expect -y
[root@141 mnt]# cat ssh.exp 
#!/usr/bin/expect
set timeout 30         #设置超时时间,永不超时则设为-1
spawn ssh root@172.25.254.79
expect "*password:"     #若出现password字符则立即返回,否则等待30s
send "westos\r"         #输入密码并回车
interact        #执行完成后保持交互状态,把控制权交给控制台

spawn是进入expect环境后的内部命令。

The spawn daemon provides the Postfix equivalent of inetd. It listens on a port as specified in the Postfix master.cf file and spawns an external command whenever a connection is established. The connection can be made over local IPC (such as UNIX-domain sockets) or over non-local IPC (such as TCP sockets). The command´s standard input, output and error streams are connected directly to the communication endpoint.

结果:运行后直接登录
[root@141 mnt]# expect ssh.exp 
spawn ssh root@172.25.254.79
root@172.25.254.79's password: 
Last login: Wed Jun 27 13:56:50 2018
Expect嵌套Shell
[root@141 mnt]# cat expect.exp 
#!/usr/bin/expect
set timeout 2
spawn /mnt/sh_expect.sh
expect "*feel:"
send "sharp\r"
expect eof           ##结束标示
shell脚本
[root@141 mnt]# cat sh_expect.sh 
#!/bin/bash
read -p "How does the air feel:" FEELING
echo "The air feels $FEELING"
[root@141 mnt]# expect expect.exp 
spawn /mnt/sh_expect.sh
How does the air feel:sharp
The air feels sharp

执行shell命令

exec sh -c {rht-vmctl start desktop}
shell嵌套expect
[root@141 mnt]# cat expect_in_shell.sh 
#!/bin/bash
passwd=$2
/usr/bin/expect <<EOF
spawn ssh root@$1
expect {
    "(yes/no)"        ##这里expect可以选择符合条件的命令执行
    {
    send "yes\r"
    expect "*password:" {send "$2\r"}
    }
    "*password:"
    {
    send "$2\r"
    }
}
expect eof
EOF
自动登录
[root@141 mnt]# sh expect_in_shell.sh 172.25.254.79 westos
spawn ssh root@172.25.254.79
root@172.25.254.79's password: 
Last login: Wed Jun 27 20:05:24 2018 from xupt.sports.com
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值