18.1.0: 网络抓包 - tcpdump



1. 命令:tcpdump

作用:转储网络里传输的内容

man page description: tcpdump - dump traffic on a network

安装:yum install tcpdump -y
语法: tcpdump [参数 [参数内容] ] [协议] and [host host address] and [port port number]

详细语法: man page description

tcpdump [ -AdDefIKlLnNOpqRStuUvxX ] [ -B buffer_size ] [ -c count ]  
[ -C file_size ] [ -G rotate_seconds ] [ -F file ]  
[ -i interface ] [ -m module ] [ -M secret ]  
[ -r file ] [ -s snaplen ] [ -T type ] [ -w file ]  
[ -W filecount ]  
[ -E spi@ipaddr algo:secret,...  ]  
[ -y datalinktype ] [ -z postrotate-command ] [ -Z user ]  
[ expression ]  

参数详解:

注意: 如果抓包的时候只能抓到某个ip单向的包,有可能就是系统进和出走的网卡设备不同,此时可以尝试使用any来抓到双向的包。

用法举例:

# -w参数转储包信息到文件
tcpdump -nn -c 10 -w /tmp/tcpdump1.cap
tcpdump: listening on eth0, link-type EN10MB (Ethernet), capture size 65535 bytes
10 packets captured
11 packets received by filter
0 packets dropped by kernel


# -r参数分析转储文件
tcpdump -r /tmp/tcpdump1.cap |head -2
reading from file /tmp/tcpdump1.cap, link-type EN10MB (Ethernet)
16:13:38.113868 IP 192.168.0.3.22 > 192.168.0.28.56918: Flags [P.], seq 3436852828:3436852972, ack 1010809782, win 543, length 144
16:13:38.163777 IP 192.168.0.28.56918 > 192.168.0.3.22: Flags [.], ack 144, win 253, length 0


# -nn参数保留host、port等为数字格式
tcpdump  -c 10 -r /tmp/tcpdump1.cap |head -2
reading from file /tmp/tcpdump1.cap, link-type EN10MB (Ethernet)
16:13:38.113868 IP web01.gateway.2wire.net.ssh > Essence-PC.gateway.2wire.net.56918: Flags [P.], seq 3436852828:3436852972, ack 1010809782, win 543, length 144
16:13:38.163777 IP Essence-PC.gateway.2wire.net.56918 > web01.gateway.2wire.net.ssh: Flags [.], ack 144, win 253, length 0
#和上面一样的命令,只是去掉了-nn参数,ip和端口都变成了name

# -Z 指定用户
tcpdump -Z root
# 针对错误:tcpdump: Couldn't find user 'tcpdump'

# 指定hostname
tcpdump host www.baidu.com

# 指定src
tcpdump src 192.168.1.1

# 指定dst
tcpdump dst 192.168.1.1

# 指定post
tcpdump port 80

生产环境实际用例

tcpdump -i any -nn -c 1000 host 192.168.1.1 and not port (22 or 3600) -w /tmp/tcpdump.result.cap

在抓包量比较大的时候,使用tcpdump查看抓包结果不是特别直观,建议是使用wireshark图形工具来查看