DevilWAH
DevilWAH

Reputation: 2643

Run tcpdump in a loop

I would like to run a script that captures traffic from a server using tcpdump and ping.

I want it to start tcpdump, pause, ping an endpoint, sleep for X number of seconds and then repeat the process. But I want it to start and stop tcpdump between each ping. I thought the code below would work but it jumps out of the loop after a single ping?

Any ideas why this is?

#!/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

Upvotes: 0

Views: 1467

Answers (1)

codeforester
codeforester

Reputation: 43039

The issue is with your range - you have an extra period there. So, you are just looping once with the string {1...4} instead of 1 2 3 4.

You could write your code as:

#!/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

Upvotes: 3

Related Questions