【发布时间】:2018-04-11 17:56:41
【问题描述】:
首先我作为脚本初学者问这个问题,目前我有一个期望脚本,它会自动登录到预定义的 Cisco 设备并运行某些命令,我想更新我的脚本,以便这个脚本也可以备份 Juniper 设备.
理想情况下,我希望脚本执行的操作是(在伪代码中)
login / send credentials
expect prompt
send command "show version"
if output contains "JUNOS" then
send command 1
send command 2
send command 3
otherwise if output contains "Cisco" then
send command 1
send command 2
send command 3
很抱歉,如果以前有人问过这个问题,但我已经尝试过搜索和搜索,但如果有人可以提供帮助,我将无法找到答案,我将不胜感激。我还包含了我当前的期望脚本供您参考(此脚本由 BASH 脚本调用)
set timeout 5
set hostname [lindex $argv 0]
set username "user"
set password "pass"
spawn ssh $username@$hostname
expect "Password:"
send "$password\n"
expect "#" {
send "terminal length 0\n"
send "show running-config\n"
expect "end\r"
send "\n"
send "exit\n"
}
---- 更新 ---
感谢您的意见 Dinesh - 我已更新我的脚本以包含您提供的内容(如下所示)
set timeout 5
set hostname [lindex $argv 0]
set username "user"
set password "pass"
set prompt "(>|#|\\\$) $"
spawn ssh $username@$hostname
expect "*assword:"
send $password\r
send \r
expect -re $prompt {
send "show version\r"
expect -re $prompt
expect *;
set output $expect_out(buffer);
#Basic string check logic with Tcl
if { [string first "JUNOS" $output ]!=-1 } {
send "show configuration | display set | no-more"
expect -re $prompt
send "exit\r"
} else {
send "terminal length 0\r"
expect -re $prompt
send "show run\r"
expect "end"
send \r
expect -re $prompt
send "exit\r"
}
}
但是,当我运行此脚本时,我遇到的问题是“显示版本”的输出似乎与我的“字符串检查”不匹配,因此脚本忽略了“if”语句并继续执行“其他”声明。
“show version”命令的输出如下 - 我需要修改什么才能匹配“JUNOS”字符串?
user@host> show version
Hostname: host
Model: srx240h
JUNOS Software Release [11.4R7.5]
--- 编辑 2:脚本输出
05c4rw@testpc:~/script$ ./ssh.sh
spawn ssh user@juniperhost
## LOGIN BANNER - Removed for brevity
user@juniperhost's password:
--- JUNOS 11.4R7.5 built 2013-03-01 11:40:03 UTC
user@juniperhost> show version
Hostname: juniperhost
Model: srx240h
JUNOS Software Release [11.4R7.5]
user@juniperhost> show configuration | display set | no-more
set version 11.4R7.5
## *** OUTPUT REMOVED FOR BREVITY / PRIVACY ***
## *** END OF OUTPUT from previous command
user@juniper> spawn ssh user@ciscohost
password:
## LOGIN BANNER - removed for brevitiy
ciscohost#05c4rw@testpc:~/script$
【问题讨论】:
-
在发送
show version之前放置代码expect *并打印output的值。在这里更新一样。 -
嗨 Dinesh,感谢您更新了配置,现在它已成功运行“if”语句,但是“else”语句似乎不起作用 - 作为测试,我有两个列表中的设备,它首先自动登录到瞻博网络,然后是思科 - 在成功完成瞻博网络部分后(如果),它登录到思科设备并在退出前坐在提示符中(不发出任何命令)跨度>
-
在这种情况下,打印输出的值(只是为了方便我们知道)并在转到
if-else循环之前检查它包含的内容。 -
由于格式问题,我已将输出放在主要问题中,谢谢。
-
我的意思是打印变量
output的值。代码不能跳过if-else循环。代码流应该使用if或else
标签: configuration scripting expect cisco