在循环中运行 tcpdump



我想运行一个脚本,使用 tcpdump 和 ping 从服务器捕获流量。

我希望它启动 tcpdump、暂停、ping 端点、休眠 X 秒数,然后重复该过程。但我希望它在每次 ping 之间启动和停止 tcpdump。我以为下面的代码会起作用,但它在一次 ping 后跳出循环?

知道为什么会这样吗?

#!/bin/bash
#start a process in the background (it happens to be a TCP HTTP sniffer on  the loopback interface, for my apache server):
for i in {1...4}
do
tcpdump host 8.8.8.8  -ttt &
sleep 1
ping -I eth0 8.8.8.8 -c 1
#.....other commands that send packets to tcpdump.....
sleep 1
pkill tcpdump
done

问题在于您的范围 - 您在那里有一个额外的时间。 因此,您只需使用字符串循环一次{1...4}而不是1 2 3 4

您可以将代码编写为:

#!/bin/bash
for i in {1..4}
do
tcpdump host 8.8.8.8 -ttt &
sleep 1
ping -I eth0 8.8.8.8 -c 1
sleep 1
kill "$!"                      # kill the background process
done

最新更新