用expect实现自动化

 在默认的情况下,expect并没有附带于多数常见的Linux发行版本中。expect必须用软件包管理器手动安装。

 expect等待特定的输入提示,通过检查输入提示来发送数据。 

[root@localhost tmp]# cat interactive.sh 
#!/bin/bash
#filename: interactive.sh
read -p "Enter number:" no;
read -p "Enter name:" name;
echo You have entered $no ,$name;

[root@localhost tmp]# cat automate_expect.sh 
#!/usr/bin/expect
#filename:automate_expact.sh
spawn ./interactive.sh
expect "Enter number:"
send "1\n"
expect "Enter name:"
send "hello\n"
expect eof

执行后的结果如下所示:

[root@localhost tmp]# ./automate_expect.sh 
spawn ./interactive.sh
Enter number:1
Enter name:hello
You have entered 1 ,hello

在上面的脚本中:

  • spawn参数指定需要自动化的哪一个命令;

  • expect参数提供需要等待的消息;

  • send是需要发送的消息;

  • expect eof指明命令交互结束。