expect脚本

#!/bin/bash
# Filename: main.sh

usage(){
 echo "scp file :./main.sh scp sourcefile destfile"
 echo "ssh exec: ./main.sh ssh command"
}

file=iplist.txt
#password='fengmao'
case $1 in
  "scp")
    
    for ip in `cat $file`; do
        ./scp.exp $ip $2 $3
    done
  ;;
  "ssh")
    for ip in `cat $file`;do
        ./ssh.exp $ip "$2"
    done
  ;;
  *)
    usage
  ;;
esac

ssh。exp

#!/usr/bin/expect -f

set ipaddr [lindex $argv 0]
set command [lindex $argv 1]
#set passwd [lindex $argv 1]
set passwd test
set timeout 30
spawn ssh root@$ipaddr
expect {
    "yes/no" {send "yes\r"; exp_continue}
    "password:" { send "$passwd\r"}
}
expect { 
#    "#*" {send "apt-get install snmp-mibs-downloader -y\r"}  
    "#*" {send "$command\r"; send "exit\r" }  
}

expect eof  

scp.exp

#!/usr/bin/expect -f

set timeout 10
set host [lindex $argv 0]
set src_file [lindex $argv 1]
set dest_file [lindex $argv 2]
set username root
set password test
spawn scp $src_file $username@$host:$dest_file
 expect {
 "(yes/no)?"
   {
    send "yes\n"
    expect "*assword:" { send "$password\n"}
 }
 "*assword:"
{
 send "$password\n"
}
}

expect "100%"
expect eof

 

iplist

192.168.0.201
192.168.0.202
192.168.0.203
192.168.0.204
192.168.0.205
192.168.0.206
192.168.0.207
192.168.0.208
192.168.0.209
192.168.0.210
192.168.0.211
192.168.0.212
192.168.0.213
192.168.0.214
192.168.0.215
192.168.0.216
192.168.0.217
192.168.0.218
192.168.0.219
192.168.0.220
192.168.0.221
192.168.0.222
192.168.0.223
192.168.0.224
192.168.0.225
192.168.0.226
192.168.0.227

http://wangxu.me/blog/p/tag/exp_continue

exp_continue心得。

“expect 的匹配可以看做是一个循环,通常匹配之后都会退出语句,但如果有 exp_continue 则可以不断循环匹配,输入多条命令 - See more at: http://wangxu.me/blog/p/tag/exp_continue#sthash.hiiDHL2Z.dpuf”

这也是为什么在第二个脚本中加入send "exit\r",如果不加它会循环。

 

posted @ 2013-11-28 14:34  silence.li  阅读(328)  评论(0编辑  收藏  举报