通過expect實現無交互式ssh遠程登錄

通過expect實現無交互式ssh遠程登錄

expect是在tcl基礎上創建起來的,它還提供了一些tcl所沒有的命令,它可以用來做一些linux下無法做到交互的一些命令操作

首先,下載安裝expect所需的源碼包

http://jaist.dl.sourceforge.net/project/tcl/Tcl/8.6.4/tcl8.6.4-src.tar.gz

http://sourceforge.net/projects/expect/files/Expect/5.45/expect5.45.tar.gz/download

在Linux系統中可以直接使用wget 命令進行下載

上傳源碼包到Linux系統

1)安裝tcl

[root@xuegod163 ~]#tar xfvz tcl8.4.11-src.tar.gz#解壓源碼包

[root@xuegod163 ~]#cd tcl8.4.11/unix
[root@xuegod163 unix]# ./configure --prefix=/usr/local/tcl --enable-shared

#配置,並啓用共享庫
[root@xuegod163 unix]# make#編譯
[root@xuegod163 unix]#make install#安裝

安裝完畢以後,進入tcl源代碼的根目錄,把子目錄unix下面的tclUnixPort.h copy到子目錄generic中。
暫時不要刪除tcl源代碼,因爲expect的安裝過程還需要用。

[root@xuegod163 unix]# cp tclUnixPort.h ../generic/

2)安裝expect

[root@xuegod163 ~]# tar zxvf expect5.45.tar.gz#解壓源碼包

[root@xuegod163 ~]# cd expect5.45
[root@xuegod163 expect5.45]# ./configure \#配置

> --prefix=/usr/local/expect \#指定安裝目錄

> --with-tcl=/usr/local/tcl/lib/ \#關聯tcl庫

> --with-include=/root/tcl8.6.4/generic/#關聯tcl接口

[root@xuegod163 expect5.45]# make#編譯

[root@xuegod163 expect5.45]# make install#安裝

[root@xuegod163 ~]# ln -s /usr/local/tcl/bin/expect /usr/bin/expect#創建鏈接

使用expect創建腳本

1)定義腳本執行的shell

#!/usr/bin/expect

這裏定義的是expect可執行文件的鏈接路徑(或真實路徑),功能類似於bash等shell功能

2)set timeout 30

設置超時時間,單位是秒,如果設爲timeout -1 意爲永不超時

3)spawn

spawn 是進入expect環境後才能執行的內部命令,不能直接在默認的shell環境中進行執行

主要功能:傳遞交互指令

4)expect

這裏的expect同樣是expect的內部命令

主要功能:判斷輸出結果是否包含某項字符串,沒有則立即返回,否則就等待一段時間後返回,等待時間通過timeout進行設置

5)send

執行交互動作,將交互要執行的動作進行輸入給交互指令

命令字符串結尾要加上"r",如果出現異常等待的狀態可以進行覈查

6)interact

執行完後保持交互狀態,把控制權交給控制檯

如果不加這一項,交互完成會自動退出

7)$argv

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

$argv0 爲腳本名本身

另外一種表示方法:

lrange $argv 0 0#表示第一個參數

lrange $argv 0 4#表示第一個到第五個參數(不包含腳本名本身)

實戰:通過expect實現無交互式ssh遠程登錄

1)一個簡單的指定登錄主機的腳本

[root@xuegod163 ~]# vim ssh.exp

#!/usr/bin/expect

set ipaddress "192.168.1.164"

set passwd "123456"

set timeout 30

spawn ssh rm@$ipaddress

expect {

"yes/no" { send "yes\r" }

"password:" { send "$passwd\r" }

}

interact

執行結果:

[root@xuegod163 ~]# ./ssh.exp

spawn ssh [email protected]

[email protected]'s password: [root@xuegod163 ~]# vim

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章