以下脚本telnet到从txt文件调用的各种设备中,然后运行命令,记录输出然后退出。但是,当使用不正确的IP地址时,脚本会显示输入的用户名和密码,这在日志文件中可见,这是不理想的。知道如何插入超时来防止这种情况吗?
#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 :(得分: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一样,我建议您在每个expect
命令后使用send
。
因此,您的脚本可以修改如下,
#!/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