linux expect自动登录ssh,ftp

expect是一种能够按照脚本内容里面设定的方式与交互式程序进行“会话”的程序。根据脚本内容,Expect可以知道程序会提示或反馈什么内容以及 什么是正确的应答。它是一种可以提供“分支和嵌套结构”来引导程序流程的解释型脚本语言。 shell功能很强大,但是不能实现有交互功能的多机器之前的操作,例如ssh和ftp.而expect可以帮助我们来实现.


1,ssh实现自动登录,并停在登录服务器上

  1. #!/usr/bin/expect -f  
  2.  set ip [lindex $argv     //接收第一个参数,并设置IP  
  3.  set password [lindex $argv   //接收第二个参数,并设置密码  
  4.  set timeout 10                   //设置超时时间  
  5.  spawn ssh root@$ip       //发送ssh请滶  
  6.  expect                 //返回信息匹配  
  7.  "*yes/no" send "yes\r"exp_continue}  //第一次ssh连接会提示yes/no,继续  
  8.  "*password:" send "$password\r"      //出现密码提示,发送密码  
  9.   
  10.  expect "#*"  
  11.  send "pwd\r" 
  12. send  "exit\r"  
  13.  expect eof  
     

远程登录到ftp,并且下载文件

  1. #!/usr/bin/expect -f  
  2.  set ip [lindex $argv  
  3.  set dir [lindex $argv  
  4.  set file [lindex $argv  
  5.  set timeout 10  
  6.  spawn ftp $ip  
  7.  expect "Name*"  
  8.  send "zwh\r"  
  9.  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  

运行结果如下:

  1. root@ubuntu:/home/zhangy# ./test2.exp 192.168.1.130 /var/www/www aaa.html  
  2. spawn ftp 192.168.1.130  
  3. Connected to 192.168.1.130.  
  4. 220 (vsFTPd 2.0.5)  
  5. Name (192.168.1.130:root): zwh  
  6. 331 Please specify the password.  
  7. Password:  
  8. 230 Login successful.  
  9. Remote system type is UNIX.  
  10. Using binary mode to transfer files.  
  11. ftp> lcd /var/www/www  
  12. Local directory now /var/www/www  
  13. ftp> get /var/www/www/aaa.html /var/www/www/aaa.html  
  14. local: /var/www/www/aaa.html remote: /var/www/www/aaa.html  
  15. 200 PORT command successful. Consider using PASV.  
  16. 150 Opening BINARY mode data connection for /var/www/www/aaa.html (66 bytes).  
  17. 226 File send OK.  
  18. 66 bytes received in 0.00 secs (515.6 kB/s)  
  19. quit aaa.html has been download  
  20. 221 Goodbye.  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值