Tuesday, September 28, 2010

Stripping The Port Off Tcpdump Output

You can use the sed command in Linux to strip off the port from tcpdump output, after using awk to pull out the IP addresses. tcpdump adds a decimal point and the port number to both the source and destination, such as, which would designate port 23 on If you wanted to capture all the source addresses on your network, you could do so with something like: tcpdump -nn -i eth0 -q | awk '{print $3}'. We're piping the output of tcpdump to the awk command instead of the screen and telling awk to print the third column. Our output, without awk,  would look something like this:
11:59:15.871010 IP > tcp 31
awk prints only the third column, separated by spaces.
To strip the last octet off, which is the port number, we could pipe the results of awk through sed, using the search and replace function, like this: sed 's/.[^.]*$//'

What we would then have would be just a column of source IP addresses. Pipe it into a text file using the redirection operator, > file1.
Now we can run that file through the sort command, to sort them numerically, and then through the uniq command, to remove duplicates, and pipe that into another filename:
sort file1 | uniq > file2.

So command 1 would be:
tcpdump -nn -i eth0 -q | awk '{print $3}' | sed 's/.[^.]*$//'  > file1 (change the -i parameter to whatever interface you will be monitoring)

And command2 would simply be:

sort file1 | uniq > file2

And file 2 can then be search, or run through a script to resolve hostnames, imported into a spreadsheet for reporting or whatever is needed.

No comments:

Blog Archive