Abstract 分析网络抓包用 python 更高效
Authors Walter Fan
Category learning note
Status v1.0
Updated 2023-01-10
License CC-BY-NC-ND 4.0

网络抓包分析用的最多的两大工具是 tcpdump 和 wireshark.

一般我们通过 tcpdump 或者 wireshark 来捕获网络包为 *.pcap 或者 *.pcapng 文件

tcpdump  -G 60 -W 1 -w /tmp/test.pcap

而分析 pcap 文件可以用 wireshark, wireshark 之强大, 界面之复杂不用赘述, 相关书籍和文章汗牛充栋.

我更喜欢用其命令行工具 tshark, 例如

tshark -P -V -x -2 -T text -j rtp -c 3 -r /tmp/test.pcap

例如将 pcapng 文件中的前 100 包按以下条件过滤出来,并导出为 json 文件

tshark -r 2022-03-30-cc.pcapng -2 -Y "ip.addr == 10.140.202.120 and rtp.p_type == 123" -V -c 100 -T json >
packet_sample.json"

输出结果如下

//省略 1 ~ 4 层的信息: 1)frame, 2)eth, 3)ip, 4)udp
"rtp": {"rtp.setup": "","rtp.setup_tree": {"rtp.setup-frame": "1","rtp.setup-method": "HEUR RTP"},"rtp.version": "2","rtp.padding": "0","rtp.ext": "1","rtp.cc": "0","rtp.marker": "0","rtp.p_type": "123","rtp.seq": "8637","rtp.extseq": "74173","rtp.timestamp": "2709737133","rtp.ssrc": "0xe19bcceb","rtp.ext.profile": "0x0000bede","rtp.ext.len": "2","rtp.hdr_exts": {"RFC 5285 Header Extension (One-Byte Header)": {"rtp.ext.rfc5285.id": "2","rtp.ext.rfc5285.len": "3","rtp.ext.rfc5285.data": "e0:9c:ac"},"RFC 5285 Header Extension (One-Byte Header)": {"rtp.ext.rfc5285.id": "3","rtp.ext.rfc5285.len": "2","rtp.ext.rfc5285.data": "c4:70"}},"rtp.payload": "92:00:60:90:80:c6:67:..."
}

更多具体用法参见 tshark –help

如果我们需要进一步地进行自动化分析,pyshark 是一个不错的库, 用 python 就可以读取分析网络包

pyshark 基本用法

1) 从抓包文件中读取网络包

>>> import pyshark
>>> cap = pyshark.FileCapture('/tmp/mycapture.cap')
>>> cap
<FileCapture /tmp/mycapture.cap (589 packets)>
>>> print cap[0]
Packet (Length: 698)
Layer ETH:Destination: BLANKEDSource: BLANKEDType: IP (0x0800)
Layer IP:Version: 4Header Length: 20 bytesDifferentiated Services Field: 0x00 (DSCP 0x00: Default; ECN: 0x00: Not-ECT (Not ECN-Capable Transport))Total Length: 684Identification: 0x254f (9551)Flags: 0x00Fragment offset: 0Time to live: 1Protocol: UDP (17)Header checksum: 0xe148 [correct]Source: BLANKEDDestination: BLANKED...

2) 从一个网络接口中读取网络包

>>> capture = pyshark.LiveCapture(interface='eth0')
>>> capture.sniff(timeout=50)
>>> capture
<LiveCapture (5 packets)>
>>> capture[3]
<UDP/HTTP Packet>for packet in capture.sniff_continuously(packet_count=5):print 'Just arrived:', packet

3) 使用环形缓冲区从一个网络接口中读取网络包

>>> capture = pyshark.LiveRingCapture(interface='eth0')
>>> capture.sniff(timeout=50)
>>> capture
<LiveCapture (5 packets)>
>>> capture[3]
<UDP/HTTP Packet>for packet in capture.sniff_continuously(packet_count=5):print 'Just arrived:', packet

4) 从一个远程网络接口读取网络包

>>> capture = pyshark.RemoteCapture('192.168.1.101', 'eth0')
>>> capture.sniff(timeout=50)
>>> capture

更多用法参见 https://github.com/KimiNewt/pyshark

综合实例

我在分析 WebRTC 中的网络梯度延迟 OWDV(One Way Delay Variation), 也用它写了一小段脚本, 性价比极高

#!/usr/bin/env python3
import pyshark
import pandas as pd
import matplotlib
import matplotlib.pyplot as pltimport argparse
from datetime import datetime"""
abs_send_time_24 = (ntp_timestamp_64 >> 14) & 0x00ffffff ;
NTP timestamp is the number of seconds since the epoch, in 32.32 bit fixed point format.
It is 24 bit 6.18 fixed point,  yielding 64s wraparound and 3.8us resolutionint kAbsSendTimeFraction = 18;
int kAbsSendTimeInterArrivalUpshift = 8;
int kInterArrivalShift = RTPHeaderExtension::kAbsSendTimeFraction + kAbsSendTimeInterArrivalUpshift;
constexpr double kTimestampToMs = 1000.0 / static_cast<double>(1 << kInterArrivalShift);
uint32_t timestamp = send_time_24bits << kAbsSendTimeInterArrivalUpshift;
Timestamp send_time = Timestamp::Millis(static_cast<int64_t>(timestamp) * kTimestampToMs);"""
# fraction part has 18 bits
kAbsSendTimeFraction = 18
kAbsSendTimeInterArrivalUpshift = 8
# after upshfit 8 bits, there are 26 bits for fraction
kInterArrivalShift = kAbsSendTimeFraction + kAbsSendTimeInterArrivalUpshiftkTimestampToMs = 1000.0 / (1 << kInterArrivalShift)def send_time_to_ms(send_time_24bits):timestamp = send_time_24bits << kAbsSendTimeInterArrivalUpshiftsend_time = timestamp * kTimestampToMsreturn send_timeclass RtpAnalyzer:def __init__(self, input_file, output_file):self._pcap_file = input_fileself._csv_file = output_filedef read_pcap(self, display_filter, count):dataList = []packets = pyshark.FileCapture(self._pcap_file, display_filter=display_filter)i = 0for packet in packets:dataItem = {}dataItem["arrival_time"] = datetime.fromtimestamp(float(packet.frame_info.time_epoch))dataItem["arrival_time_ms"] = float(packet.frame_info.time_epoch) * 1000dataItem["rtp_timestamp"] = int(packet.rtp.timestamp)dataItem["extseq"] = int(packet.rtp.extseq)dataItem["packet_size"] = int(packet.udp.length)if int(packet.rtp.ext_rfc5285_id) == 2:send_time_24bits = packet.rtp.ext_rfc5285_data.main_field.hex_valuedataItem["abs_send_time"] = send_time_to_ms(send_time_24bits)dataList.append(dataItem)i += 1if i >= count:breakdataFrame = pd.DataFrame(dataList)#print(dataFrame)return dataFramedef calculate_delta(self, df, row_interval=1):df["arrival_time_ms_diff"] = df["arrival_time_ms"].diff(periods=row_interval)df["send_time_diff"] = df["abs_send_time"].diff(periods=row_interval)df["OWDV"] = df["arrival_time_ms_diff"] - df["send_time_diff"]df["OWDV"] = df["OWDV"].abs()df = df[df['OWDV'] < 60]print(df)df.to_csv(self._csv_file)print(df["OWDV"].describe())print("* note: filter out OWDV if it > 60s because abs_send_time wrap around by 64s")return dfdef draw_chart(self, chart_file, df, x, y):plt.style.use('seaborn-v0_8-whitegrid')fig = plt.figure(figsize=(36, 18))font = {'size': 16}plt.plot(x, y, data=df)#plt.show()fig.savefig(chart_file)plt.close()if __name__ == '__main__':parser = argparse.ArgumentParser()parser.add_argument('-i', action='store', dest='input_file', help='specify input file')parser.add_argument('-o', action='store', dest='output_file', help='specify output file')parser.add_argument('-f', action='store', dest='filter', default="rtp", help='specify filter expression')parser.add_argument('-c', action='store', dest='count', default=10, help='specify packet count')args = parser.parse_args()if not args.input_file or not args.output_file or not args.output_file.endswith(".csv"):print("usage: ./rtp_analyze.py -i <pcap_file> -f <filter_expression>")print('such as: ./rtp_analyze.py -i /tmp/test_owdv.pcap -o "test_owdv.csv" -f "rtp.ssrc==0x8ab92fad" -c 100000')exit(0)rtpAnalyzer = RtpAnalyzer(args.input_file, args.output_file)df = rtpAnalyzer.read_pcap(args.filter, int(args.count))if not df.empty:df = rtpAnalyzer.calculate_delta(df)rtpAnalyzer.draw_chart("{}.png".format(args.output_file[:-4]), df, "arrival_time",  "OWDV")

上述小程序生成的图片如下

参考资料

  • TShark: https://www.wireshark.org/docs/man-pages/tshark.html
  • Pyshark: https://github.com/KimiNewt/pyshark


本作品采用 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。

http://www.taodudu.cc/news/show-6591874.html

相关文章:

  • 12Python爬虫---Fiddler抓包工具使用
  • 用户角色权限的简单理解
  • 闻风丧胆系统角色权限五张表的设计
  • SSL和SSH协议简单介绍。
  • SSL协议的概述(三)
  • SSL协议概述(三)
  • SSRF中利用到的协议
  • SSL协议工作在OSI模型中的哪一层?
  • 图森未来将被摘牌:股价重挫29% 侯晓迪已在内斗中出局
  • 高等数学:可微,可导关系详解
  • 硬盘被格式化后数据如何恢复(在mac电脑上抹掉了)
  • Mac磁盘格式化与系统重装
  • 怎么在Mac上修复/格式化磁盘?
  • 解决uefi模式安装Linux无引导问题
  • UEFI模式和Legacy模式的区别
  • 【OS基础】UEFI与 Legacy BIOS两种启动模式详解
  • UEFI启动模式和传统的Lagency启动模式
  • 关于win操作系统引导模式:UEFI
  • AutoCAD 2010(让你的CAD都是正版)简体中文版注册机
  • 只有想法还不够,还要有计划和行动
  • 行为日志分析思路与想法
  • 有想法还要有办法,总结各种策划方案
  • 我们要做个有想法的员工,但是不能瞎想。
  • 怎样做一个有想法的人-《思考的艺术》读后感
  • 192.168.和10.0.开头的IP、内网IP段、IP简介、分类
  • WAP教程[转]
  • 拥有WWB 让您WAP更轻松
  • 简介WAP最新版本:WAP 2.0(转)
  • wap网站
  • wap 应用

分析网络抓包用 python 更高效相关推荐

  1. 怎样对Android设备进行网络抓包

    问题描写叙述: 前段时间自己的app訪问server的url总是会出现间接性失败的问题,于是和server的同事开了个会.提出了他们server存在的这个bug,我的同事自然说自己的server没问题 ...

  2. xmpp协议抓包_开源网络抓包与分析框架学习-Packetbeat篇

    开源简介 packbeat是一个开源的实时网络抓包与分析框架,内置了很多常见的协议捕获及解析,如HTTP.MySQL.Redis等.在实际使用中,通常和Elasticsearch以及kibana联合使 ...

  3. 计算机网络抓包参考文献,计算机网络课程设计二(网络抓包与分析)

    <计算机网络课程设计二(网络抓包与分析)>由会员分享,可在线阅读,更多相关<计算机网络课程设计二(网络抓包与分析)(9页珍藏版)>请在人人文库网上搜索. 1.课程设计课程名称: ...

  4. python微服务监控_基于网络抓包实现kubernetes中微服务的应用级监控

    微服务是什么? 此话题不是本文重点,如你还不知道.请谷歌一波,会有遍地的解释.引用下图说明下微服务可能呈现的形态: 微服务监控的挑战 监控的目的是为了让集群中所有的服务组件,不管是HTTP服务,数据库 ...

  5. Python下的网络抓包库

    一直以来对于Python下的网络抓包库很疑惑,搞不清楚pylibpcap.pypcap.pycap这些库之间是什么关系,混沌了很长时间,在网上G了很久慢慢搞清楚了,其实这些都是libpcap的Pyth ...

  6. Python使用网络抓包的方式,利用超级鹰平台识别验证码登录爬取古诗文网、上篇--识别验证码

    Python使用网络抓包的方式,利用超级鹰平台识别验证码登录,<爬取古诗文网>. 上篇–识别验证码 序言: 哈喽,各位小可爱们,我又来了,这次我新学习到的内容是python爬虫识别验证码. ...

  7. python 网络抓包

    Python下的网络抓包库pylibpcap.pypcap.pycap这些库其实这些都是libpcap的Python绑定实现,libpcap才是真正的核心. 在http://pypi.python.o ...

  8. Java抓包+分析网络数据包

    Java抓包+分析网络数据包   本程序基于java语言,需安装winpcap和配置Jpcap.jar库文件(需要的可以评论留下邮箱),成功实现了对本主机网卡接口的显示和网络数据包的抓取,并调用函数对 ...

  9. 【Fidder网络抓包+Python爬虫】下载微信小程序视频

    首先声明本篇博客以学习为目的,侵权即删. 文章目录 1. Fidder抓包 1.1 在电脑上打开微信小程序视频播放页以及Fidder软件 1.2 点击视频播放按钮,并查看Fidder抓到的数据包 2. ...

最新文章

  1. 4场直播,哈工大、亚马逊等大咖为你带来机器学习与知识图谱的内容盛宴
  2. Metadata Lock原理2
  3. 什么是CGI、FastCGI、PHP-CGI、PHP-FPM
  4. Uninstall Office 2016 for Mac
  5. CommandBehavior.CloseConnection的使用
  6. java之hibernate之基于外键的一对一单向关联映射
  7. java dispatchevent_java事件处理机制
  8. javaEE之--------统计站点在线人数,安全登录等(观察者设计模式)
  9. 1018 锤子剪刀布 (20 分)—PAT (Basic Level) Practice (中文)
  10. sylixos pci
  11. 变异数分析_人工智能系统中分析变异的祸害
  12. 【大地信】新时代GIS发展趋势与未来展望
  13. 【原创】常用元器件选型目录-cayden(待续)
  14. 服务器能打开其他网站打不开,为什么有的网页打不开其他能打开(浏览器网页打不开的原因有哪些)...
  15. 公司职员薪水管理系统(List)
  16. ​Apache 软件基金会 2021 年度报告亮点解读
  17. 张晓龙2018微信公开课
  18. 同一目录下批处理执行Word宏
  19. 遇到Process finished with exit code -1073740791 (0xC0000409)实在不能解决的时候要注意
  20. 毕业设计管理系统 数据库设计

热门文章

  1. 2021年低压电工考试题库及低压电工模拟考试
  2. ASEMI代理ADI亚德诺LTC3309AEV#TRMPBF车规级芯片
  3. video DownLoad Mothed
  4. spring 事务传播行为实例分析
  5. 小巧实用的音视频剪辑工具大集合
  6. 通勤时间超过一个小时的工作,你能接受吗?
  7. 团队角色解析的最佳做法
  8. IBM serverx服务器RAID阵列磁盘配置JBOD模式(直通模式)
  9. jquery插件备忘录
  10. jQuery判断复选框是否被选中的3种方式