使用 Expect Script 从文本文件中读取两列

Using Expect Script to read two columns from text file

我需要在 Expect 上编写脚本来读取包含两列的文本文件。第一列是站点名称 (dns),第二列是路由器接口,当我从 Cisco 路由器执行 FTP 功能时,它将用作源接口。这是文本文件的内容 (myfile.txt):

site1   Gi0/0/0.44
site2   GigabitEthernet0/0
site3   GigabitEthernet0/0
site4   GigabitEthernet0/0/0
site5   GigabitEthernet0/0/0

这是我的代码。它只能读取第一列。 您将看到一个名为 "source-int" 的变量,它尚未在任何地方定义。我只是把它作为占位符放在脚本中。

#!/usr/bin/expect
#
#
set workingdir cisco/rtr
puts stdout "Enter TACACS Username:"
gets stdin tacuserid
system stty -echo
puts stdout "Enter TACACS password:"
gets stdin tacpswd
puts stdout "\nEnter enable password:"
gets stdin enabpswd
system stty echo
#
set RTR [open "$workingdir/myfile.txt" r]
#
while {[gets $RTR dnsname] != -1} {
if {[ string range $dnsname 0 0 ] != "#"} {
        send_user "The value of the router name is $dnsname\n"
        set timeout 10
        set count 0
        log_file -a -noappend $workingdir/session_$dnsname\_$timestamp.log
        send_log "### /START-SSH-SESSION/ IP: $dnsname @ [exec date] ###\n"
        spawn ssh -o StrictHostKeyChecking=no -l $tacuserid $dnsname
expect -ex "TACACS Password: "
send "$tacpswd\r"
expect ">"
send "enable\r"
expect "assword: "
send "$enabpswd\r"
expect "#"
send "config t\r"
expect "#"
send "no ip ftp passive\r"
expect "#"
send "ip ftp username anonymous\r"
expect "#"
send "ip ftp source-interface $souce-int\r"
expect "#"
send "ip ftp password cisco\r"
expect "#"
send "end\r"
expect "#"
send "copy ftp://10.10.10.1/out/customer/ACL.txt flash:\r"
expect "\?"
send "\r"
expect "#"
send "end\r"
expect "#"
send "exit\r"
send_log "\n"
send_log "### /END-SSH-SESSION/ IP: $dnsname @ [exec date] ###\n"
log_file
sleep 5
        }
}
exit

非常感谢任何帮助。 谢谢!

您可以使用 tcl 的 regexp 命令将行拆分为 2 个单词。

if {[regexp {(\S+)\s+(\S+)} "$dnsname" dummy dns interface] == 1} {
    puts "dns=$dns interface=$interface"
}

正则表达式代码 \s 匹配空白字符,\S 匹配非空白字符。 + 后缀匹配 1 个或多个前面的代码。 () 捕获想要的部分,它们由命令放入变量 dnsinterface.