1. 程式人生 > >在shell指令碼中使用expect實現scp傳輸問題

在shell指令碼中使用expect實現scp傳輸問題

1.安裝expect

expect用於shell指令碼中自動互動,其是基於tcl程式語言的工具。所以安裝expect首先安裝tcl。本文中使用的是expect5.45tcl8.6.6

安裝tcl

[root@tseg0 /]$ mkdir /tools
[root@tseg0 /]$ tar -zxvf tcl8.6.6-src.tar.gz
[root@tseg0 /]$ cd tcl8.6.6/unix/
[root@tseg0 /]$ ./configure
[root@tseg0 /]$ make
[root@tseg0 /]$ make install

安裝expect

[root@tseg0 /]$ cd /tools
[root@tseg0
/]$ tar -zxvf expect5.45.tar.gz [root@tseg0 /]$ cd expect5.45/ [root@tseg0 /]$ ./configure --with-tcl=/usr/local/lib/ --with-tcl include=/tools/tcl8.6.6/generic/ [root@tseg0 /]$ make [root@tseg0 /]$ make install

shell指令碼實現scp傳輸

命令解釋

-c 表示可以在命令列下執行except指令碼;
spawn 命令啟用一個unix程式來互動,就是在之後要執行的命令;
expect “aaa” 表示程式在等待這個aaa的字串;
send 向程式傳送字串,expect和send經常是成對出現的,比如當expect“aaa”的時候,send“bbb”。

執行指令碼

#! /bin/sh
expect -c "
    spawn scp -r /home/tseg/hello $name@10.103.240.33:/home/$name/
    expect {
        \"*assword\" {set timeout 300; send \"$pass\r\"; exp_continue;}
        \"yes/no\" {send \"yes\r\";}
    }
expect eof"

解釋:
第二行: -c 表示可以不用與控制檯互動;
第三行:spawn啟用一個scp的unix程式;
第五行:expect期待含有“assword”的字串,設定連線時間最大為300毫秒,如果出現這個字串,就send 變數pass代表的密碼字串, exp_continue表示執行下面的匹配;
第六航:expect期待含有“assword”的字串,設定連線時間最大為300毫秒,如果出現這個字串,就send 變數pass代表的密碼字串;
第八行:表示結束。