shell補充工具-expect linux 下面,在shell編程裡面,有些程式的輸入是需要接收tty的輸入而不是stdin的輸入,如果需要一種實現,那麼就是expect。 一,安裝expect1yum install expect 二,執行個體1,ssh實現自動登入,並停在登入伺服器上 01#!/usr/bin/expect -f02 set ip www.factj.com03 set password [lindex $argv 0 ] //接收第一個參數,並設定密碼04 set timeout 10 //設定逾時時間05 spawn ssh root@$ip //發送ssh請滶06 expect { //返回資訊匹配07 "*yes/no" { send "yes\r"; exp_continue} //第一次ssh串連會提示yes/no,繼續08 "*password:" { send "$password\r" } //出現密碼提示,發送密碼09 }10 interact //互動模式,使用者會停留在遠程伺服器上面. 運行結果如下:1root@factj:/home/factj# ./test.exp factj2spawn ssh root@w<span></span> Last login: Fri Sep 7 10:47:43 2013 from www.factj.com3[root@linux ~]# 這個例子有統一的介面,根據IP和密碼可以串連到不同的機器.如果你嫌輸入IP和密碼麻煩,看下面的例子 01#!/usr/bin/expect -f02 set ip www.factj.com03 set password factj04 set timeout 1005 spawn ssh root@$ip06 expect {07 "*yes/no" { send "yes\r"; exp_continue}08 "*password:" { send "$password\r" }09 }10interact運行結果如下: 1root@ubuntu:/home/zhangy# ./web.exp2spawn ssh factj@www.factj.com3Last login: Fri Agu 7 12:59:02 2013 from www.factj.com4[root@linux ~]#2,ssh遠程登入到伺服器,並且執行命令,執行完後並退出 01#!/usr/bin/expect -f02 set ip www.factj.com03 set password factj04 set timeout 1005 spawn ssh root@$ip06 expect {07 "*yes/no" { send "yes\r"; exp_continue}08 "*password:" { send "$password\r" }09 }10 expect "#*"11 send "pwd\r"12 send "exit\r"13 expect eof 運行結果如下: 01root@ubuntu:/home/zhangy# ./test3.exp02spawn ssh root@www.factj.com03root@www.factj.com's password:04Last login: Fri agu 7 14:05:07 2013 from 116.246.27.9005[root@localhost ~]# pwd06/root07[root@localhost ~]# exit08logout09 10Connection to www.factj.com closed.3,遠程登入到ftp,並且下載檔案 01#!/usr/bin/expect -f02 set ip [lindex $argv 0 ]03 set dir [lindex $argv 1 ]04 set file [lindex $argv 2 ]05 set timeout 1006 spawn ftp $ip07 expect "Name*"08 send "zwh\r"09 expect "Password:*"10 send "zwh\r"11 expect "ftp>*"12 send "lcd $dir\r"13 expect {14 "*file" { send_user "local $_dir No such file or directory";send "quit\r" }15 "*now*" { send "get $dir/$file $dir/$file\r"}16 }17 expect {18 "*Failed" { send_user "remote $file No such file";send "quit\r" }19 "*OK" { send_user "$file has been download\r";send "quit\r"}20 }21 expect eof 運行結果如下: 01root@ubuntu:/home/zhangy# ./test2.exp www.factj.com /var/www/www aaa.html02spawn ftp www.factj.com03Connected to www.factj.com.04220 (vsFTPd 2.0.5)05Name (www.factj.com:root): zwh06331 Please specify the password.07Password:08230 Login successful.09Remote system type is UNIX.10Using binary mode to transfer files.11ftp> lcd /var/www/www12Local directory now /var/www/www13ftp> get /var/www/www/aaa.html /var/www/www/aaa.html14local: /var/www/www/aaa.html remote: /var/www/www/aaa.html15200 PORT command successful. Consider using PASV.16150 Opening BINARY mode data connection for /var/www/www/aaa.html (66 bytes).17226 File send OK.1866 bytes received in 0.00 secs (515.6 kB/s)19quit aaa.html has been download20221 Goodbye.