Tuesday, May 25, 2010

piping tcpdump output to lsof

This simple Bash script will output the lsof end of any foreign network connection:
[Set to the interface of your choice]
while [ 1 ]
        do
                for i in `tcpdump -i rl0 -c 1 -l dst $(hostname) | awk '{print $2}' | awk -F"." '{print $1"."$2"."$3"."$4}'`
                         do lsof -i@$i
                done
done
with time/date stamp added and headers removed:
while [ 1 ]

        do
                for i in `tcpdump -i rl0 -c 1 -l dst $(hostname) | awk '{print $2}' | awk -F"." '{print $1"."$2"."$3"."$4}'`
                         do echo `date -u` `lsof -i@$i | grep -v PID`
                done
done

Run like this:
./tcp_lsof.sh >> tcp.lsof.log &

the script produces output like this:

COMMAND   PID     USER   FD   TYPE     DEVICE SIZE/OFF NODE NAME
sshd    18392 rferrisx    5u  IPv4 0xd699ac80      0t0  TCP rmflaptop.rmfdevelopment.com:ssh->192.168.0.3:13974 (ESTABLISHED)
sshd    29850     root    5u  IPv4 0xd699ac80      0t0  TCP rmflaptop.rmfdevelopment.com:ssh->192.168.0.3:13974 (ESTABLISHED)
or
Wed May 26 15:22:06 UTC 2010 sshd 9448 root 5u IPv4 0xd699ac80 0t0 TCP rmflaptop.rmfdevelopment.com:ssh->192.168.0.3:15729 (ESTABLISHED) 
sshd 29734 rferrisx 5u IPv4 0xd699ac80 0t0 TCP rmflaptop.rmfdevelopment.com:ssh->192.168.0.3:15729 (ESTABLISHED)
Wed May 26 15:22:07 UTC 2010 sshd 9448 root 5u IPv4 0xd699ac80 0t0 TCP rmflaptop.rmfdevelopment.com:ssh->192.168.0.3:15729 (ESTABLISHED) 
sshd 29734 rferrisx 5u IPv4 0xd699ac80

No comments:

Post a Comment