- 工信部備案號 滇ICP備05000110號-1
- 滇公安備案 滇53010302000111
- 增值電信業(yè)務(wù)經(jīng)營許可證 B1.B2-20181647、滇B1.B2-20190004
- 云南互聯(lián)網(wǎng)協(xié)會理事單位
- 安全聯(lián)盟認(rèn)證網(wǎng)站身份V標(biāo)記
- 域名注冊服務(wù)機(jī)構(gòu)許可:滇D3-20230001
- 代理域名注冊服務(wù)機(jī)構(gòu):新網(wǎng)數(shù)碼
如果想寫一個能夠自動處理輸入輸出的腳本又不想面對C或Perl,那么expect是最好的選擇。它可以用來做一些Linux下無法做到交互的一些命令操作。
(1).安裝和使用expect
expect是不會自動安裝的所以需要使用命令進(jìn)行安裝,這里使用yum即可:
1 | [root@xuexi ~]# yum -y install expect |
在腳本中使用expect的方法一般有兩種:
第一種、定義腳本執(zhí)行的shell時,定義為expect。即腳本第一行為#!/bin/expect或#!/usr/bin/expect;
第二種、在shell腳本中使用時,可以使用一組/usr/bin/expect<<EOF和EOF來對expect調(diào)用。
(2).expect中參數(shù)和語法說明
set [變量名] "[String]"
在expect腳本中設(shè)置變量需要在前面使用set,否則無法使用。
set timeout 30
設(shè)置超時時間,單位為秒,如果設(shè)為timeout -1則永不超時。
spawn
spawn是進(jìn)入expect環(huán)境后才能執(zhí)行的內(nèi)部命令,如果沒有安裝expect或直接在默認(rèn)shell下執(zhí)行是找不到spawn命令的。它主要的功能是開啟腳本和命令之間的會話。(后面跟隨的命令必須是需要交互的,因為expect腳本是用來做交互應(yīng)用的)
expect
這里的expect同樣是expect的內(nèi)部命令。主要功能是判斷輸出結(jié)果是否包含某項關(guān)鍵字,沒有則立即返回,否則等待一段時間后返回,等待時間通過set timeout進(jìn)行設(shè)置。有兩種寫法:
1 2 3 4 5 6 7 8 9 10 11 12 | expect{ "[String1]" {send "[sendString1]\r" ;exp_continue} "[String2]" {send "[sendString2]\r" ;exp_continue} ... "[StringN]" {send "[sendStringN]\r" } } 或 expect "String" send "sendString1\r" sned "sendString2\r" ... expect eof |
send
執(zhí)行交互動作,將交互要執(zhí)行的動作輸入。命令字符串結(jié)尾要加上"\r",如果出現(xiàn)異常等待狀態(tài)可以進(jìn)行核查
exp_continue
繼續(xù)執(zhí)行接下來的交互操作
interact
執(zhí)行完后保持交互狀態(tài),把控制權(quán)交給控制臺;如果沒有這一項,交互完成后會自動退出
$argv
expect腳本可以接受從bash傳遞過來的參數(shù),可以使用[Iindex $argv n]獲得,n從0開始表示第一個參數(shù)。
注意:spawn開啟會話,expect和send進(jìn)行交互。
(3).腳本實例
1)expect腳本實現(xiàn)ssh免交互
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | [root@xuexi ~]# cat ssh-6.exp #!/bin/expect set ipaddr "192.168.1.6" set name "root" set passwd "123456" set timeout 30 spawn ssh $name@$ipaddr expect "password" send "$passwd\r" expect eof expect "#" send "ls /etc/ >> /root/1.txt\r" send "exit\r" expect eof [root@xuexi ~]# expect ssh-6.exp spawn ssh root@192.168.1.6 root@192.168.1.6's password: Last login: Sat May 11 18:24:27 2019 from xuexi [root@youxi1 ~]# ls /etc/ >> /root/1.txt [root@youxi1 ~]# exit 登出 Connection to 192.168.1.6 closed. |
在192.168.1.6上可以看到生成了/root/1.txt
2)shell腳本實現(xiàn)免交互
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | [root@xuexi ~]# cat ssh-6.sh #!/bin/bash name= "root" passwd= "123456" ipaddr= "192.168.1.6" /bin/expect << EOF set timeout 30 spawn ssh $name@$ipaddr expect "password" send "$passwd\r" expect eof expect "#" send "ls /etc/ >> /root/2.txt\r" send "exit\r" expect eof EOF [root@xuexi ~]# sh ssh-6.sh spawn ssh root@192.168.1.6 root@192.168.1.6's password: Last login: Sat May 11 19:21:18 2019 from xuexi [root@youxi1 ~]# ls /etc/ >> /root/2.txt [root@youxi1 ~]# exit
|