gpt4 book ai didi

tcl - 如何搜索存储在列表中的多个模式,直到找到所有项目或经过一定时间

转载 作者:行者123 更新时间:2023-12-04 20:45:38 25 4
gpt4 key购买 nike

我正在制作一个简单的 expect 脚本,它将监视 tcpdump 的输出以获取多播地址列表。我想知道在预期超时之前是否从列表中的每个多播地址接收到数据包。

我有一个可行的解决方案,但它效率低下,我相信我没有充分利用 expect 和 tcl 的功能。无论如何,这是我当前的脚本:

set multicast_list {225.0.0.1 225.0.0.2 225.0.0.3}

send "tcpdump -i ixp1\r"
# If tcpdump does not start, unzip it and run it again
expect {
"tcpdump: listening on ixp1" {}
"sh: tcpdump: not found" {
send "gunzip /usr/sbin/tcpdump.gz\r"
expect "# "
send "tcpdump -i ixp1\r"
exp_continue
}
}
# Set timeout to the number of seconds expect will check for ip addresses
set timeout 30
set found [list]
set not_found [list]
foreach ip $multicast_list {
expect {
"> $ip" { lappend found "$ip" }
timeout { lappend not_found "$ip" }
}
}
set timeout 5
# Send ^c to stop tcpdump
send -- "\003"
expect "# "

因此,正如您所看到的,脚本将一次查找每个 IP 地址,如果看到该 IP,它会将其添加到找到的地址列表中。如果预期超时,它将将该地址添加到 not_found 列表并搜索下一个地址。

现在回到我的问题:有没有一种方法可以在给定的时间内同时监视所有 IP 地址的 tcpdump。如果要找到地址,我想将它添加到找到的地址列表中,并且最好不要期待它(这可能不可能,我不确定)。关键是我需要脚本来并行监视列表中的所有 IP。我无法对每个地址进行硬编码,因为它们每次都会不同,而且我要查找的地址数量也会有所不同。我真的可以从一个期待的大师那里得到一些帮助,哈哈。

谢谢你!

最佳答案

这是一个有趣的问题。最简单的方法可能是对expect 脚本的核心进行运行时生成。幸运的是,Tcl 非常擅长这种事情。 (注意:我假设 IP 地址都是 IPv4 地址并且仅由数字和句点组成;如果它是插入的一般字符串,我必须更加小心。)

set timeout 30
set found [list]
set not_found [list]
# Generate the timeout clause as a normal literal
set expbody {
timeout {
set not_found [array names waiting]
unset waiting
}
}
foreach ip $multicast_list {
set waiting($ip) "dummy"
# Generate the per-ip clause as a multi-line string; beware a few backslashes
append expbody "\"> $ip\" {
lappend found $ip
unset waiting($ip)
if {\[array size waiting\]} exp_continue
}\n"
}
# Feed into expect; it's none-the-wiser that it was runtime-generated
expect $expbody
set timeout 5
# Send ^c to stop tcpdump
send -- "\003"
expect "# "

您可能想要 puts $expbody前几次,这样你就可以确定它在做正确的事情。

关于tcl - 如何搜索存储在列表中的多个模式,直到找到所有项目或经过一定时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18371497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com