2

I am trying to save the output of a grep filter to a file.

I want to run tcpdump for a long time, and filter a certain IP to a file.

tcpdump -i eth0 -n -s 0 port 5060 -vvv | grep "A.B.C."

This works fine. It shows me IP's from my network.

But when I add >> file.dump at the end, the file is always empty.

My script:

tcpdump -i eth0 -n -s 0 port 5060 -vvv | grep "A.B.C." >> file.dump

And yes, it must be grep. I don't want to use tcpdump filters because it gives me millions of lines and with grep I get only one line per IP.

How can I redirect (append) the full output of the grep command to a file?

Dan Lowe
  • 51,713
  • 20
  • 123
  • 112
tom8823
  • 41
  • 4
  • Did you try this one : `tcpdump -i eth0 -n -s 0 port 5060 -vvv | grep 'A.B.C.' > file.dump` ? – Alex Dec 28 '15 at 15:47
  • Yes I tried, doesn't work and I want to use append, not overwrite – tom8823 Dec 28 '15 at 15:48
  • This is because `tcpdump` provides a continuous stream, probably through stderr. Does it work if you say `tcpdump ... |& grep --line-buffered "A.B.C."`? – fedorqui Dec 28 '15 at 15:52
  • If you try without grep (only for test purposes) does it correctly write into the file ? @fedorqui yes it works for me at least, I'm able to append a file from the tcpdump command (I mean, without the --line-buffered switch). – Alex Dec 28 '15 at 15:52
  • 1
    Yes! It's working with "& grep --line-buffered". Thanks fedorqui – tom8823 Dec 28 '15 at 16:00

1 Answers1

5

The output of tcpdump is probably going through stderr, not stdout. This means that grep won't catch it unless you convert it into stdout.

To do this you can use |&:

tcpdump -i eth0 -n -s 0 port 5060 -vvv |& grep "A.B.C."

Then, it may happen that the output is a continuous stream, so that you somehow have to tell grep to use line buffering. For this you have the option --line-buffered option.

All together, say:

tcpdump ... |& grep --line-buffered "A.B.C" >> file.dump
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598