有的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 # 指明命令交互結束