我写了一个脚本来通过ssh登录并运行一些命令。列表中我设备列表中的一半设备具有不同的可接受用户名和密码组合。
我希望能够解释失败的登录,使用相同的设备启动新的登录尝试,但在第二次尝试时使用不同的登录凭据(有两种可能的用户名和密码组合)
如果有人能指出我正确的方向,我真的很感激。这是我第一次使用TCL或期待。
到目前为止,我所拥有的精简版本如下。
set username "someusername"
set password "somepassword"
set devices "X.X.X.X"
foreach device $devices {
puts "Processing device: $device";
spawn plink -ssh $devices
expect "Store key in cache"
send "y\r"
expect "login as:"
send "$username\r"
expect "password:"
send "$password\r"
expect "#"
send "conf t\r"
expect "(config)#"
send "some commands\r"
expect "(config)#"
send "end\r"
expect "#"
send "copy run startup-config\r"
expect "#"
答案 0 :(得分:1)
你可能需要像
这样的东西set usernames [list name1 name2]
set passwords [list pw1 pw2 ]
set devices [list X.X.X.X ...]
foreach device $devices {
puts "Processing device: $device";
spawn plink -ssh $devices
set auth_idx -1
expect {
"Store key in cache" {send "y\r"; exp_continue}
"login as:" {
incr auth_idx
if {$auth_idx == [llength $usernames]} {
puts "login failed for $device"
# close the plink connection. I'm guessing here
send \003 ;# Ctrl-C
expect eof
# and on to the next device
continue
}
send "[lindex $usernames $auth_idx]\r"
expect "password:"
send "[lindex $passwords $auth_idx]\r"
# and wait for either the command prompt or another login prompt
exp_continue
}
"#"
}
# ... whatever you do when you're logged in
# and logout. something like
send "quit\r"
expect eof
}
这使用exp_continue
在同一期望语句中“循环”。我假设您可能不一定要将密钥存储在缓存中。我还假设如果第一次登录尝试失败,您会看到“登录为”
更新
set usernames [list name1 name2]
set passwords [list pw1 pw2 ]
set devices [list X.X.X.X ...]
set device_idx 0
set auth_idx 0
while {$device_idx < [llength $devices]} {
set device [lindex $devices $device_idx]
puts "Processing device: $device";
spawn plink -ssh $devices
expect {
"Store key in cache" {send "y\r"; exp_continue}
"login as:" {
send "[lindex $usernames $auth_idx]\r"
expect "password:"
send "[lindex $passwords $auth_idx]\r"
exp_continue
}
"Access denied" {
incr auth_idx
if {$auth_idx == [llength $usernames]} {
puts "login failed for $device"
# next device
set auth_idx 0
incr device_idx
} else {
# close the plink connection. I'm guessing here
send \003 ;# Ctrl-C
expect eof
# re-do with current device
}
continue
}
"#"
}
# ... whatever you do when you're logged in
# and logout. something like
send "quit\r"
expect eof
# and on to the next device
set auth_idx 0
incr device_idx
}