有的shell脚本需要交互输入,如果需要批量或者自动化,可以根据实际情况按照如下方法处理
1.重定向
这个方法很简单,把需要输入的内容按每行写入到文档中,然后运行脚本
./vpncmd < content
2.使用管道
echo -e "3\n" | ./vpncmd
3.使用expect
expect是专门用来交互自动化的工具,但它有可能不是随系统就安装好的,有时需要自己手工安装该命令
yum install expect -y
可参考如下脚本
[root@host vpnserver]# cat expect_test.sh
#!/usr/bin/expect #注意这行,不是/bin/sh
spawn ./vpncmd # 指定需要将哪个命令自动化
expect "Select 1, 2 or 3:" # 需要等待的消息
send "1\n" # 是要发送的命令
expect "Hostname of IP Address of Destination:"
send "127.0.0.1\n"
expect "Specify Virtual Hub Name:"
send "\n"
expect "Password:"
send "ashq\n"
expect "VPN Server>"
send "hublist\n"
expect "VPN Server>"
send "exit\n"
#interact
expect off # 指明命令交互结束