2015-11-03 110 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