如何在TCL/expect命令文件中引用脚本预定义变量?
解决Expect脚本中commands.txt变量替换的问题
核心问题是Expect默认会把从文件读取的行当作纯字符串发送,不会自动展开其中的TCL变量。要实现变量替换,只需在发送前用TCL的subst命令处理读取到的每一行内容。
具体实现步骤
预定义变量:在脚本开头先定义好需要用到的变量,比如:
set ip "192.168.2.2" set gw "10.0.0.1"读取命令文件并处理变量:读取commands.txt的每一行后,先用
subst展开变量,再发送给设备。修改后的核心代码片段如下:# 打开命令文件 set cmd_file [open "commands.txt" r] set commands [split [read $cmd_file] "\n"] close $cmd_file # 匹配Cisco提示符后逐行处理命令 expect "*#" foreach line $commands { # 跳过空行 if {$line eq ""} {continue} # 用subst展开变量,再发送命令 set expanded_line [subst $line] send "$expanded_line\r" expect "*#" }处理特殊场景:如果commands.txt中包含TCL的特殊符号(比如
[]、{}),而你不希望这些符号被当作TCL命令执行,可使用subst -nocommands参数,只展开变量,忽略命令执行:set expanded_line [subst -nocommands $line]
示例验证
假设commands.txt内容如下:
interface GigabitEthernet0/1 ip address $ip 255.255.255.0 ip route 0.0.0.0 0.0.0.0 $gw exit
经过subst处理后,发送给交换机的实际命令会变成:
interface GigabitEthernet0/1 ip address 192.168.2.2 255.255.255.0 ip route 0.0.0.0 0.0.0.0 10.0.0.1 exit
注意事项
- 确保所有在commands.txt中使用的变量都已在脚本中提前定义,否则
subst会保留$符号,导致发送的命令包含未替换的变量名。 - 如果需要处理带转义的
$(即不想替换的$),可在commands.txt中写成\$,subst会将其转换为普通的$符号。
内容的提问来源于stack exchange,提问作者Andrea
相关产品推荐
相关产品推荐

