我有这部分 TCL/期望代码:
commands.txt sample content:
configure terminal
interface Vlan10
ip address 192.168.1.1 255.255.255.0
set commands "commands.txt"
#
set f [open "$commands"]
set commands [split [read $f] "\n"]
close $f
#
foreach cmd $commands {
expect {
"*#" {
send "$cmd\n"
}
它按预期工作,对于发送到交换机的每个命令,它确实“期望 Cisco 提示符 *#,然后逐行发送列表中的命令,末尾带有换行符”。
现在我想在命令文件中使用之前在脚本中设置的变量(例如:set ip "192.168.2.2"),如下所示:
cat commands.txt
configure terminal
Interface Vlan10
ip address $ip 255.255.255.0
我该怎么做?
现在,变量被忽略,并且显然被作为文字字符串发送。 例如:
ip address $ip 255.255.255.0
谢谢
使用
subst
命令:https://www.tcl.tk/man/tcl8.4/TclCmd/subst.htm
它执行所有常见的字符串插值,例如用于变量替换的
$
和用于命令替换的 []
以及用于反斜杠替换的 \
。
您只能通过使用正确的参数将其限制为变量替换:
send "[subst -nocommand -nobackslashes $cmd]\n"