本文共 2903 字,大约阅读时间需要 9 分钟。
$ sudo apt-get install expect
命令含义
#!/usr/bin/expectset timeout 30spawn ssh root@192.168.1.1expect "password:"send "mypassword\r"interact
set 设置变量
spawn 执行命令
expect 检测点
send 发送指令
例 7.1. example for expect
cat tech-support.exp#!/usr/bin/expectset timeout 30spawn telnet 172.16.1.24expect "Password: "send "chen\r"expect "*>"send "enable\r"expect "Password: "send "chen\r"expect "*#"send "sh tech-support\r"send "!\r"expect "*-Switch#"send "exit\r"expect eofexit
3层设备
cisco.exp#!/usr/bin/expectset ip [lindex $argv 0]set username [lindex $argv 1]set password [lindex $argv 2]log_file $ip.logspawn telnet $ipexpect "Username:"send "$username\r"expect "Password:"send "$password\r"expect "#"send "show running-config\r"send "exit\r"expect eof
2层设备
$ cat config.exp#!/usr/bin/expectset timeout 30set host [lindex $argv 0]set password [lindex $argv 1]set done 0log_file $host.logspawn telnet $hostexpect "Password:"send "$password\r"expect "*>"send "enable\r"expect "Password: "send "$password\r"expect "*#"send "show running-config\r"while {$done == 0} {expect {" --More--" { send -- " " }"*#" { set done 1 }eof { set done 1 }}}send "\r"expect "*#"send "exit\r"expect eofexit$ cat loop.sh#! /bin/shwhile read swdo ./config.exp $swdone <
例 7.2. example for expect
#!/usr/bin/expectset timeout 30spawn ssh root@192.168.1.1expect "password:"send "mypassword\r"interact
例 7.3. example 1
#!/usr/bin/expect set password 1234 #密码 #download spawn scp /www/* root@172.16.1.2:/www/ set timeout 300 expect "172.16.1.2's password:" set timeout 3000 #exec sleep 1 send "$password\r" set timeout 300 send "exit\r" #expect eof interact spawn scp /www/* root@172.16.1.3:/www/ set timeout 300 expect "root@172.16.1.3's password:" set timeout 3000 #exec sleep 1 send "$password\r" set timeout 300 send "exit\r" interact
例 7.4. *.exp
$ expect autossh.exp neo@192.168.3.10 chen "ls /"
autossh.exp
#!/usr/bin/expect -fset ipaddress [lindex $argv 0]set ipaddress [lindex $argv 0]set passwd [lindex $argv 1]set command [lindex $argv 2]set timeout 30spawn ssh $ipaddressexpect { "yes/no" { send "yes\r";exp_continue } "password:" { send "$passwd\r" }}expect ""send "$command \r"send "exit\r"expect eofexit
批量执行
password.lst192.168.0.1 passwd192.168.0.2 passwd192.168.0.3 passwd
#!/bin/bashcat password.lst | while read linedo host=$(echo $line|awk '{print $1}') passwd=$(echo $line|awk '{print $2}') expect autossh.exp $host $passwd sleep 2done
#! /usr/bin/expect -fspawn scp 1 neo@192.168.0.1:expect "*password:"send "your password\r"expect eof
#!/bin/expectspawn scp x.x.x.xfor {} {1} {} { expect { "password:" { send "YourPassWord" } }}
spawn scp 1 neo@172.16.0.1:for { set i 1 } {$i<5} {incr i} { expect { "*password:" {send "koven\r"} "*(yes/no)*" {send "yes\r"} }}