2015-11-03 109 views
0

以下脚本telnet到从txt文件调用的各种设备中,然后运行命令,记录输出并退出。但是,如果使用错误的IP地址,脚本将显示输入的用户名和密码,并且这在日志文件中是不可见的。任何想法如何插入超时以防止这种情况?Expect脚本telnet超时问题

#telnet.exp 
###################################################### 

#!/usr/bin/expect -f 

# Set variables 
set hostname [lindex $argv 0] 
set username [lindex $argv 2] 
set password [lindex $argv 1] 

# Log the output 
log_file -a ~/configuration-telnet.log 

# Which device we are working on and at what time 
send_user "\n" 
send_user ">>>>> Working on $hostname @ [exec date] <<<<<\n" 
send_user "\n" 

spawn telnet $hostname 
expect "Username:" 
send "$username\n" 

expect "Password:" 
send "$password\n" 
expect "#" 

send "term len 0\r" 
send "show running-config\r" 
expect "end\r" 
send "\r" 
send "exit\r" 

######################################################## 
#telnet.sh 
######################################################## 
#!/bin/bash 
echo -n "Username:" 
read -s -e username 
echo -ne '\n' 
echo -n "Password:" 
read -s -e password 
echo -ne '\n' 
# Feed the expect script a device list & the collected passwords 
for device in `cat telnet-device-list.txt`; do 
./telnet.exp $device $password $username; 
done 

回答

0

为了使timeout事件,您可以将其添加为模式这是一个内置的命令相匹配的超时。

基本思路可以是这样的,

expect { 
    pattern {some_action_here} 
    timeout {puts "timeout_here"} 
} 

为了使通用于所有类型的命令,它可以与expect_after命令一概而论。

expect_after timeout {puts "timeout happened in the script"; exit 0} 

正如我刚才所说before,我建议你到每个send命令后使用expect

所以,你的脚本可以做如下修改,

#!/usr/bin/expect -f 

# Set variables 
set hostname [lindex $argv 0] 
set username [lindex $argv 2] 
set password [lindex $argv 1] 

# Log the output 
log_file -a ~/configuration-telnet.log 

# Which device we are working on and at what time 
send_user "\n" 
send_user ">>>>> Working on $hostname @ [exec date] <<<<<\n" 
send_user "\n" 

expect_after timeout {puts "Timeout happened; So, exiting....";exit 0} 

spawn telnet $hostname 
expect "Username:" 
send "$username\r" 
expect "Password:" 
send "$password\r" 
expect "#" 
send "term len 0\r" 
expect "#" 
send "show running-config\r" 
expect "end" 
send "\r" 
expect "#" 
send "exit\r"; 
# After sending 'exit' telnet session will be closed 
# So, waiting for 'eof' 
expect eof 

如果你刻意想单独写超时操作,那么你可以把它重新写这样,

expect { 
    timeout { puts "username timeout"; exit 0} 
    "Username:" 
} 
send "$username\r" 
expect { 
    timeout { puts "password timeout"; exit 0} 
    "Password:" 
} 
send "$password\r" 
expect { 
    timeout { puts "prompt timeout"; exit 0} 
    "#" 
} 

注:

默认值timeout的值为10秒。它甚至可以改变为

set timeout 60; # Timeout value of 1 min