shell补充工具-expect

linux 下面,在shell编程里面,有些程序的输入是须要接收tty的输入而不是stdin的输入,若是须要一种实现,那么就是expect。

一,安装expect
html

yum install expect


二,实例
1,ssh实现自动登陆,并停在登陆服务器上
java

#!/usr/bin/expect -f
 set ip www.factj.com
 set password [lindex $argv 0 ]   //接收第一个参数,并设置密码
 set timeout 10                   //设置超时时间
 spawn ssh root@$ip       //发送ssh请滶
 expect {                 //返回信息匹配
 "*yes/no" { send "yes\r"; exp_continue}  //第一次ssh链接会提示yes/no,继续
 "*password:" { send "$password\r" }      //出现密码提示,发送密码
 }
 interact          //交互模式,用户会停留在远程服务器上面.

 运行结果以下:
root@factj:/home/factj# ./test.exp factj
spawn ssh root@w Last login: Fri Sep  7 10:47:43 2013 from www.factj.com
[root@linux ~]#


这个例子有统一的接口,根据IP和密码能够链接到不一样的机器.若是你嫌输入IP和密码麻烦,看下面的例子
linux

#!/usr/bin/expect -f
 set ip www.factj.com
 set password factj
 set timeout 10
 spawn ssh root@$ip
 expect {
 "*yes/no" { send "yes\r"; exp_continue}
 "*password:" { send "$password\r" }
 }
interact
运行结果以下:
root@ubuntu:/home/zhangy# ./web.exp
spawn ssh factj@www.factj.com
Last login: Fri Agu  7 12:59:02 2013 from www.factj.com
[root@linux ~]#
2,ssh远程登陆到服务器,而且执行命令,执行完后并退出
#!/usr/bin/expect -f
 set ip www.factj.com
 set password factj
 set timeout 10
 spawn ssh root@$ip
 expect {
 "*yes/no" { send "yes\r"; exp_continue}
 "*password:" { send "$password\r" }
 }
 expect "#*"
 send "pwd\r"
 send  "exit\r"
 expect eof
 运行结果以下:
root@ubuntu:/home/zhangy# ./test3.exp
spawn ssh root@www.factj.com
root@www.factj.com's password:
Last login: Fri agu 7 14:05:07 2013 from 116.246.27.90
[root@localhost ~]# pwd
/root
[root@localhost ~]# exit
logout

Connection to www.factj.com closed.
3,远程登陆到ftp,而且下载文件
#!/usr/bin/expect -f
 set ip [lindex $argv 0 ]
 set dir [lindex $argv 1 ]
 set file [lindex $argv 2 ]
 set timeout 10
 spawn ftp $ip
 expect "Name*"
 send "zwh\r"
 expect "Password:*"
 send "zwh\r"
 expect "ftp>*"
 send "lcd $dir\r"
 expect {
 "*file"  { send_user "local $_dir No such file or directory";send "quit\r" }
 "*now*"  { send "get $dir/$file $dir/$file\r"}
 }
 expect {
 "*Failed" { send_user "remote $file No such file";send "quit\r" }
 "*OK"     { send_user "$file has been download\r";send "quit\r"}
 }
 expect eof
 运行结果以下:
root@ubuntu:/home/zhangy# ./test2.exp www.factj.com /var/www/www aaa.html
spawn ftp www.factj.com
Connected to www.factj.com.
220 (vsFTPd 2.0.5)
Name (www.factj.com:root): zwh
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> lcd /var/www/www
Local directory now /var/www/www
ftp> get /var/www/www/aaa.html /var/www/www/aaa.html
local: /var/www/www/aaa.html remote: /var/www/www/aaa.html
200 PORT command successful. Consider using PASV.
150 Opening BINARY mode data connection for /var/www/www/aaa.html (66 bytes).
226 File send OK.
66 bytes received in 0.00 secs (515.6 kB/s)
quit aaa.html has been download
221 Goodbye.

文章同时发布在 http://www.factj.com/archives/364.html web

相关文章
相关标签/搜索