python读取数据流_python3+pyshark读取wireshark数据包并追踪telnet数据流

一、程序说明

本程序有两个要点,第一个要点是读取wireshark数据包(当然也可以从网卡直接捕获改个函数就行),这个使用pyshark实现。pyshark是tshark的一个python封装,至于tshark可以认为是命令行版的wireshark,随wireshark一起安装。

第二个要点是追踪流,追踪流在wireshark中是“tcp.stream eq 70”之类的形式,但是70这类值暂是不知道具体怎么计算出来的,但从网上资料看,是依据[IP address A, TCP port A, IP address B, TCP port B]四元组计算出来的,只要这四个值一样那么计算出来的tcp.stream也就一样,就认为是同一个流。那么,反过来也就是说“tcp.stream eq 70”这种形式,其实等价于"ip.addr == ip_a and tcp.port == port_a and ip.addr == ip_b and tcp.port == port_b"的形式,我们这里就是用这种形式来追踪telnet流。

至于为什么一再强调是追踪telnet流而不是追踪流,是因为感觉各应用层协议没有统一获取应用层协议内容的方法,比如这里通过tmp_packet[highest_layer_name].get_field('data')形式读取telnet数据的,但http则得用tmp_packet['http'].file_data读取,ftp等其他协议又要通过其他不同属性来获取。

另外还要说明的一点是,数据包的每次过滤主要是借助写display_filter重新读取数据包文件,而不是将所有数据包读入后自己写代码进行过滤(就实际来看这种方法比借助写display_filter重新读取数据包文件要复杂且运行速度要慢)或者写display_filter进行二次过滤(tshark本身就不支持二次过滤,就观察来看wireshark自己也没有二次过滤这种东西在执行过滤器表达式时都是重新读取数据包文件)

运行效果如下:

二、程序源代码

importpysharkclasswireshark_analysis_script():#此函数的作用是封装一下pyshark.FileCapture

defread_packets_from_file(self,packets_file_path,tshark_path,display_filter):

packets_file_obj= pyshark.FileCapture(input_file=packets_file_path,tshark_path=tshark_path,display_filter=display_filter)returnpackets_file_obj#此函数的作用是从传送过来的所有数据包中,抽取并返回{ip_server,ip_client,port_server,port_client}四元组

defget_target_client_ip_port(self,packets_file_obj):for tmp_packet inpackets_file_obj:

ip_server=tmp_packet.ip.src

port_server=tmp_packet.tcp.srcport

ip_client=tmp_packet.ip.dst

port_client=tmp_packet.tcp.dstportyield {"ip_server":ip_server,"port_server":port_server,"ip_client":ip_client, "port_client":port_client}#此函数的作用是读取传过来的所有数据包应用层的数据,并打印

deffollow_tcp_stream(self,packets_file_obj,ip,port):for tmp_packet inpackets_file_obj:

highest_layer_name=tmp_packet.highest_layerif ((tmp_packet.ip.dst == ip) and (tmp_packet.tcp.dstport ==port)):print("server(%s:%s)->client(%s:%s): %s" % (tmp_packet.ip.src, tmp_packet.tcp.srcport, tmp_packet.ip.dst, tmp_packet.tcp.dstport, tmp_packet[highest_layer_name].get_field('data')))elif ((tmp_packet.ip.src == ip) and (tmp_packet.tcp.srcport ==port)):print("client(%s:%s)->server(%s:%s): %s" % (tmp_packet.ip.src, tmp_packet.tcp.srcport, tmp_packet.ip.dst, tmp_packet.tcp.dstport, tmp_packet[highest_layer_name].get_field('data')))if __name__ == '__main__':#要读取的wireshark数据包的所在的路径

packets_file_path = 'F:\\PycharmProjects\\telnet\\pyshark_pack'

#tshark程序所在的路径,tshark随wireshark安装

tshark_path = 'D:\\tools\\Wireshark\\tshark.exe'

#过滤器表达式,与在wireshark中使用时的写法完全相同

first_step_filter = 'telnet contains "HiLinux"'

#用于存放要追踪流的ip和端口

target_client_ip_port =[]#实例化类

wireshark_analysis_script_instance =wireshark_analysis_script()#使用first_step_filter过滤器表达式,过滤出要追踪流的数据包

first_step_obj =wireshark_analysis_script_instance.read_packets_from_file(packets_file_path, tshark_path, first_step_filter)#从要追踪流的数据包中抽取出ip和端口

target_client_ip_port =wireshark_analysis_script_instance.get_target_client_ip_port(first_step_obj)

first_step_obj.close()#遍历要追踪流的ip+端口组合

for target_client_ip_port_temp intarget_client_ip_port:

ip_server= target_client_ip_port_temp['ip_server']

port_server= target_client_ip_port_temp['port_server']

ip_client= target_client_ip_port_temp['ip_client']

port_client= target_client_ip_port_temp['port_client']#这里是追踪流的关键,所有数据包中如果数据包中{ip_server,ip_client,port_server,port_client}四元组相同,那么就认为是同一个流

#当然追踪流一般都是追踪应用层的数据流,所以加上应用层协议运行过滤去掉三次握手四次挥手等没有应用层数据的数据包;我这里要追踪telnet数据流,所以除四元组外还加了telnet做过滤

second_step_filter = 'telnet and ip.addr == %s and ip.addr == %s and tcp.port == %s and tcp.port == %s' %(ip_server,ip_client,port_server,port_client)

second_step_obj=wireshark_analysis_script_instance.read_packets_from_file(packets_file_path, tshark_path, second_step_filter)print("[%s:%s]" %(ip_client, port_client))#调用follow_tcp_stream将认为是同一个流的所有数据包的应用层数据打印

wireshark_analysis_script_instance.follow_tcp_stream(second_step_obj, ip_client, port_client)

second_step_obj.close()

三、使用与wireshark一致的形式【20180929更新】

在前边的解决方案中,我们使用"ip.addr == ip_a and tcp.port == port_a and ip.addr == ip_b and tcp.port == port_b"等价代替wireshark中“tcp.stream eq 70”的形式来实现追踪流,当时的想法是不知道某个流的70这种值如何计算。

现在发现这种值pyshark在tcp.stream属性直接给出了,所以我们完全可以使用和wireshark的“tcp.stream eq 70”一致的形式来追踪流。第二大节程序可等介修改如下。

(当然因为是等价形式所以输出结果还是一样的,都是要重新解析数据包文件所以效率也就差不多,主要是为了说追流可以使用和wireshark一样的形式)

importpysharkclasswireshark_analysis_script():#此函数的作用是封装一下pyshark.FileCapture

defread_packets_from_file(self, packets_file_path, tshark_path, display_filter):

packets_file_obj= pyshark.FileCapture(input_file=packets_file_path, tshark_path=tshark_path, display_filter=display_filter)returnpackets_file_obj#此函数的作用是从传送过来的所有数据包中,抽取并返回{ip_server,ip_client,port_server,port_client}四元组

defget_target_client_ip_port(self, packets_file_obj):for tmp_packet inpackets_file_obj:

ip_server=tmp_packet.ip.src

port_server=tmp_packet.tcp.srcport

ip_client=tmp_packet.ip.dst

port_client=tmp_packet.tcp.dstport

stream_value=tmp_packet.tcp.streamyield {"ip_server": ip_server, "port_server": port_server, "ip_client": ip_client, "port_client": port_client,"stream_value":stream_value}#此函数的作用是读取传过来的所有数据包应用层的数据,并打印

deffollow_tcp_stream(self, packets_file_obj, ip, port):for tmp_packet inpackets_file_obj:

highest_layer_name=tmp_packet.highest_layer#追踪流时会有握手挥手tcp将其排除

if highest_layer_name != "TCP":if ((tmp_packet.ip.dst == ip) and (tmp_packet.tcp.dstport ==port)):print("server(%s:%s)->client(%s:%s): %s" % (tmp_packet.ip.src, tmp_packet.tcp.srcport, tmp_packet.ip.dst, tmp_packet.tcp.dstport, tmp_packet[highest_layer_name].get_field('data')))elif ((tmp_packet.ip.src == ip) and (tmp_packet.tcp.srcport ==port)):print("client(%s:%s)->server(%s:%s): %s" % (tmp_packet.ip.src, tmp_packet.tcp.srcport, tmp_packet.ip.dst, tmp_packet.tcp.dstport, tmp_packet[highest_layer_name].get_field('data')))if __name__ == '__main__':#要读取的wireshark数据包的所在的路径

packets_file_path = 'F:\\PycharmProjects\\telnet\\pyshark_pack'

#tshark程序所在的路径,tshark随wireshark安装

tshark_path = 'D:\\tools\\Wireshark\\tshark.exe'

#过滤器表达式,与在wireshark中使用时的写法完全相同

first_step_filter = 'telnet contains "HiLinux"'

#用于存放要追踪流的ip和端口

target_client_ip_port =[]#实例化类

wireshark_analysis_script_instance =wireshark_analysis_script()#使用first_step_filter过滤器表达式,过滤出要追踪流的数据包

first_step_obj =wireshark_analysis_script_instance.read_packets_from_file(packets_file_path, tshark_path, first_step_filter)#从要追踪流的数据包中抽取出ip和端口

target_client_ip_port =wireshark_analysis_script_instance.get_target_client_ip_port(first_step_obj)

first_step_obj.close()#遍历要追踪流的ip+端口组合

for target_client_ip_port_temp intarget_client_ip_port:#stream的值

stream_value = target_client_ip_port_temp['stream_value']

ip_client= target_client_ip_port_temp['ip_client']

port_client= target_client_ip_port_temp['port_client']#tcp.stream eq 70形式。为了排除tcp其实可以再直接加上and telnet

second_step_filter = 'tcp.stream eq %s' %(stream_value)

second_step_obj=wireshark_analysis_script_instance.read_packets_from_file(packets_file_path, tshark_path, second_step_filter)print("[%s:%s]" %(ip_client, port_client))#调用follow_tcp_stream将认为是同一个流的所有数据包的应用层数据打印

wireshark_analysis_script_instance.follow_tcp_stream(second_step_obj, ip_client, port_client)

second_step_obj.close()

View Code

参考:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/468929.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Windows环境下的安装gcc

Windows具有良好的界面和丰富的工具,所以目前linux开发的流程是,windows下完成编码工作,linux上实现编译工作。 为了提高工作效率,有必要在windows环境下搭建一套gcc,gdb,make环境。 MinGW就是windows下gcc的版本。 下载地址ht…

RuntimeError: NCCL error in:XXX,unhandled system error, NCCL version 2.7.8

项目场景: 分布式训练中遇到这个问题, 问题描述 大概是没有启动并行运算???( 解决方案: (1)首先看一下服务器GPU相关信息 进入pytorch终端(Terminal&#x…

Codeforces Round #371 (Div. 2) C. Sonya and Queries —— 二进制压缩

题目链接:http://codeforces.com/contest/714/problem/C C. Sonya and Queriestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday Sonya learned about long integers and invited all her friends to …

一张倾斜图片进行矫正 c++_专业性文章:10分钟矫正骨盆前倾

如今,骨盆前倾(又称“下交叉综合征”)非常多,大部分是由于以下两个原因而变得越来越突出:经常久坐不良的运动习惯后面我们讲到纠正骨盆前倾的四个基本步骤,让你快速解决,提高生活质量知识型和系统型的内容,…

vue.js源码学习分享(五)

//配置项var config {/*** Option merge strategies (used in core/util/options)//选项合并策略*/optionMergeStrategies: Object.create(null),/*** Whether to suppress warnings.//是否抑制警告*/silent: false,/*** Show production mode//生产模式 tip message on boot?…

TypeError: can‘t convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory

项目场景&#xff1a; 运行程序&#xff0c;出现报错信息 TypeError: cant convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.。 Traceback (most recent call last):File "tools/demo.py", line 97, in <module>vi…

Secure CRT 自动记录日志

配置自动log操作如下&#xff1a; 1.options ---> Global Options 2、General->Default Session->Edit Default Settings 3、Terminal->Log File 设置如图上所示 点击 日志 &#xff0c;在选项框中 Log file name中填入路径和命名参数&#xff1a; E:\Log\%Y_%M_…

java 异步调用方法_乐字节Java编程之方法、调用、重载、递归

一、概述方法是指人们在实践过程中为达到一定目的和效果所采取的办法、手段和解决方案。所谓方法&#xff0c;就是解决一类问题的代码的有序组合&#xff0c;是一个功能模块。编程语言中的方法是组合在一起来执行操作语句的集合。例如&#xff0c;System.out.println 方法&…

git clone 从GitHub上下载项目到服务器上运行+创建虚拟环境

1. 基础的Linux命令 可先进入需要放置文件的路径之下 pwd # 可看当前路径 cd …/ #返回上一层目录 cd ./xx/ #进入当前路径下的下一个文件2. GitHub项目clone到服务器上运行 # 复制GitHub页面的链接&#xff0c;在服务器后台输入git clone 命令即可 git clone https://githu…

[笔记] FireDAC DataSet 导入及导出 JSON

刚好需要将 FireDAC DataSet (TFDDataSet, TFDQuery...) 转成 JSON&#xff0c;网上找了一圈&#xff0c;原来从 XE6 开始就支持这个功能了&#xff1a; 储存&#xff1a; DataSet1.SaveToFile(d:\Data.json, TFDStorageFormat.sfJSON); 载入&#xff1a; DataSet1.LoadFromFil…

recovery相关的FAQ总结

一、[FAQ12481]Recovery mode在cache/recovery目录下新建一支文件&#xff0c;重启后&#xff0c;新建文件消失了 [DESCRIPTION] 1、在recovery.cpp文件的最后新建一支文件 /cache/recovery/wetest&#xff1b;并写入内容&#xff1a;welcome to recovery mode&#xff01; 2、…

AttributeError: module ‘torch.jit‘ has no attribute ‘_script_if_tracing‘

项目场景&#xff1a; torvh使用提示 AttributeError: module torch.jit has no attribute _script_if_tracing 原因分析&#xff1a; 解决办法&#xff1a;原因是torch与torchvision版本不匹配导致的&#xff0c;重新安装torchvision即可 解决方案&#xff1a; pip install…

java 调用python_Java平台如何调用Python平台?

1. 问题描述Java平台要调用Pyhon平台已有的算法&#xff0c;为了减少耦合度&#xff0c;采用Pyhon平台提供Restful 接口&#xff0c;Java平台负责来调用&#xff0c;采用HttpJson格式交互。2. 解决方案2.1 JAVA平台侧2.1.1 项目代码public static String invokeAlgorithm(Strin…

C 实现 删除字符串空白符的函数 strtrim

说在前面的话 字符串操作在很多C语言比赛里面都有涉及&#xff0c;最近公众号里面的C语言比赛&#xff0c;都是两个关于字符串操作的题目&#xff0c;希望大家认真看题目。 直接上代码 /*************************************************************************> Fil…

小工具:批量替换文件夹下所有文件内容中的指定词

问题描述&#xff1a; 数据集中的xml信息所标注的文件后缀写错了&#xff0c;应该为jpg&#xff0c;因此需要将所有xml文件的.png修改为.jpg 解决代码&#xff1a; 函数作用&#xff1a;找出某文件夹下的包含指定关键词文件列表&#xff0c;并将关键字修改为目标字并将新内容…

jvm性能监控工具

jvm可能存在的问题&#xff1a; OutOfMemoryError&#xff1a;内存不足 内存泄露 线程死锁 锁竞争(Lock Contention) Java消耗过多的CPU一、jps(java virtual machine process status tool)监控jvm进程转台信息jps [options] [hostid] -m&#xff1a;输出传入…

javascript犀牛书_犀牛书作者:最该忘记的JavaScript特性

作者&#xff1a; 李松峰转发链接&#xff1a;https://mp.weixin.qq.com/s/guAN1Cz2gYfKdBhmUpLyVA前言JavaScript这门语言的第一个演示版差不多就在25年前诞生。没记错的话&#xff0c;25年前的今天&#xff0c;1995年5月10日&#xff0c;星期三&#xff0c;我刚刚过了创造Jav…

RuntimeError: Integer division of tensors using div or / is no longer supported, and in a future rel

项目场景&#xff1a; 提示&#xff1a;新版python在pytorch中张量与原始数据的除法计算问题。 问题描述 报错 RuntimeError: Integer division of tensors using div or / is no longer supported, and in a future release div will perform true division as in Python 3…

Weblogic(4)—— Linux环境Weblogic12c配置节点管理(nodemanage.properties)来开启应用服务器(server)及线程池配置...

Linux环境搭建weblogic12c服务器&#xff0c;用来进行weblogic服务器项目部署&#xff0c;刚创建weblogic服务器会默认存在AdminServer管理服务器。但是项目应用一般是不能挂在这个服务器上的&#xff0c;需要自己单独创建应用服务器。 使用root权限登录 服务器&#xff1a; 输…