大名鼎鼎的网络抓包分析包工具wireshark的终端命令行形式--tshark,除了交互式图像化界面,但凡wireshark具有的功能,它都具有。
Linux中安装命令:
sudo apt-get install tshark
在终端中打开后,直接输入不含任何参数控制的tshark 命令后,会自动进行数据包抓取,分组信息逐一在终端呈现,Ctrl+c结束抓包过程。
使用tshark捕获网络流量
tshark -w ~/Desktop/test.pcap -c 10
上述命令行实现对网络流量分组抓取,将前10个分组抓取并存储到/home/mumu/Desktop路径下的命名文件test.pcap中,网络接口默认第一个(可以使用tsark -D查看所有可用网络接口)
对已存储分组信息通过参数控制获得目标属性内容,如:提取帧数、帧相对时间、源头IP地址、目的地IP地址、数据包协议,以及来自之前捕获的网络流量的网络数据包的长度,键入命令:
tshark -r login.tcpdump -T fields -e frame.number -eframe.time_relative -e ip.src -e ip.dst -e
frame.protocols -e frame.len -E header=y -E quote=n -E occurrence=f
-E header=y选项指令tshark先输出报头行。-E quote=n规定tshark不包括引号里面的数据,而-E occurrence=f指令tshark使用有多个occurrence的字段的头一个occurrence。
输出结果:
frame.number frame.time_relative ip.src frame.protocols frame.len
1 0.000000000 192.168.0.106 eth:ethertype:ip:tcp 74
2 4.600294664 192.168.0.1 eth:ethertype:ip:udp:data 147
3 4.600846088 192.168.0.1 eth:ethertype:ip:udp:ssdp 303
4 4.601003537 192.168.0.1 eth:ethertype:ip:udp:ssdp 312
5 4.601231011 192.168.0.1 eth:ethertype:ip:udp:ssdp 375
6 4.601380060 192.168.0.1 eth:ethertype:ip:udp:ssdp 312
7 4.601607844 192.168.0.1 eth:ethertype:ip:udp:ssdp 351
8 4.601773182 192.168.0.1 eth:ethertype:ip:udp:ssdp 312
9 4.601954529 192.168.0.1 eth:ethertype:ip:udp:ssdp 371
10 4.602168547 192.168.0.1 eth:ethertype:ip:udp:ssdp 367
下述代码实现对存储的分组信息,分析其ip地址的有效性,代码文本命名为checkIP.py
import socket
import sys
import re
def valid_ip(address):
try:
# 将点分十进制字符串数据转换为二进制字符串
socket.inet_aton(address)
return True
except:
return False
total = 0
valid = 0
invalid = 0
for line in sys.stdin:
total = total + 1
line = line.rstrip('\n')
if valid_ip(line):
valid = valid + 1
else:
invalid = invalid + 1
#显示已检查的IP地址总数
print("Total number of IPs checked:",total)
print("Valid IPs found:",valid)
print("Invalid IPs found:",invalid)
终端键入命令:
tshark -r ~/networkData.pcap -T fields -e ip.src | python checkIP.py
终端结果显示:
Total number of IPs checked: 10
Valid IPs found: 8
Invalid IPs found: 2