久久青草精品A片狠狠,日韩欧美视频一区二区,亚洲国码AV日韩,国产精品黄在

expect實現免交互

2019-09-05 18:09:08 8717

如果想寫一個能夠自動處理輸入輸出的腳本又不想面對C或Perl,那么expect是最好的選擇。它可以用來做一些Linux下無法做到交互的一些命令操作。

(1).安裝和使用expect

  expect是不會自動安裝的所以需要使用命令進行安裝,這里使用yum即可:

1
[root@xuexi ~]# yum -y install expect

  在腳本中使用expect的方法一般有兩種:

    第一種、定義腳本執行的shell時,定義為expect。即腳本第一行為#!/bin/expect或#!/usr/bin/expect;

    第二種、在shell腳本中使用時,可以使用一組/usr/bin/expect<<EOF和EOF來對expect調用。

(2).expect中參數和語法說明

  set [變量名] "[String]"

  在expect腳本中設置變量需要在前面使用set,否則無法使用。

  set timeout 30

  設置超時時間,單位為秒,如果設為timeout -1則永不超時。

  spawn

  spawn是進入expect環境后才能執行的內部命令,如果沒有安裝expect或直接在默認shell下執行是找不到spawn命令的。它主要的功能是開啟腳本和命令之間的會話。(后面跟隨的命令必須是需要交互的,因為expect腳本是用來做交互應用的

  expect

  這里的expect同樣是expect的內部命令。主要功能是判斷輸出結果是否包含某項關鍵字,沒有則立即返回,否則等待一段時間后返回,等待時間通過set timeout進行設置。有兩種寫法:

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

  執行交互動作,將交互要執行的動作輸入。命令字符串結尾要加上"\r",如果出現異常等待狀態可以進行核查

  exp_continue

  繼續執行接下來的交互操作

  interact

  執行完后保持交互狀態,把控制權交給控制臺;如果沒有這一項,交互完成后會自動退出

  $argv

  expect腳本可以接受從bash傳遞過來的參數,可以使用[Iindex $argv n]獲得,n從0開始表示第一個參數。

  注意:spawn開啟會話,expect和send進行交互。

(3).腳本實例

 1)expect腳本實現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腳本實現免交互

      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

      提交成功!非常感謝您的反饋,我們會繼續努力做到更好!

      這條文檔是否有幫助解決問題?

      非常抱歉未能幫助到您。為了給您提供更好的服務,我們很需要您進一步的反饋信息:

      在文檔使用中是否遇到以下問題: