except script用于模拟用户交互
一个简单的script脚本如下
#!/usr/bin/expect
set ip x.x.x.x
set user root
set passwd xxx
set timeout 10
spawn ssh $user@$ip -p36000
expect {
"(yes/no)" {send "yes\r"; exp_continue}
"password:" {send "$passwd\r"}
}
expect "*]#" {send "echo 'login +1' >> ~/remote_login.log\r"};
expect "*]#" {send "ls ~/\r"};
expect "*]#" {send "exit\r"};
expect eof;
下面的except script可以接受参数,然后通过ssh执行cmd
#!/usr/bin/expect
set timeout 30
proc help {} {
puts {Usage: -h <host> -P <port> -u <user> -p <passwd> --timeout <second> [cmd] }
}
if {$argc<4} { help ; exit 1}
set port 36000
set user root
#set passwd "1bH!NOe4#u$!s+"
set passwd "123"
set host ""
set cmd ""
set passwderror 0
for {set i 0} {$i<$argc} {} {
set m [lindex $argv $i]
switch -- $m {
"-h" {
set host [lindex $argv [expr 1+$i ]]
incr i 2
}
"-P" {
set port [lindex $argv [expr 1+$i ]]
incr i 2
}
"-u" {
set user [lindex $argv [expr 1+$i ]]
incr i 2
}
"-p" {
set passwd [lindex $argv [expr 1+$i ]]
incr i 2
}
"--timeout" {
set tmptimeout [lindex $argv [expr 1+$i ]]
if { $tmptimeout != "0" } {
set timeout $tmptimeout
}
incr i 2
}
default {
set cmd [lindex $argv $i]
incr i 1
}
}
}
spawn ssh -o "UserKnownHostsFile=/dev/null" -o "StrictHostKeyChecking=no" -p$port $host -l$user "$cmd"
expect {
"*assword:*" {
if { $passwderror == 1 } {
puts "account or password is error"
exit 2
}
set passwderror 1
send "$passwd\r"
exp_continue
}
"*es/no)?*" {
send "yes\r"
exp_continue
}
"yes/no" {
send "yes\r"
exp_continue
}
"*Network is unreachable*" {
exit 4
}
"*Connection refused*" {
exit 5
}
"*Bad port*" {
exit 6
}
timeout {
puts "connect is timeout"
exit 3
}
"Host key verification failed*" {
exit 7
}
-nocase "*REMOTE HOST IDENTIFICATION HAS CHANGED*" {
exit 7
}
-nocase "*host key has just been changed*" {
exit 7
}
-nocase "*connection timed out*" {
exit 3
}
-nocase "*lost connection*" {
exit 9
}
}
网友评论