首页 > 编程 > Python > 正文

python 的 scapy库,实现网卡收发包的例子

2019-11-25 12:16:07
字体:
来源:转载
供稿:网友

问题:

测试时 收发流采用TestCenter、SmartBit等仪表来进行。如果仍采用其进行自动化冒烟,则会带来效率低、成本高的问题。

解决方案:

采用网卡来收发流,虽然有性能统计上的缺陷,但可以验证一些基本功能,且经济。

采用scapy模块,

1-获取计算机网卡的iface,并预先设计好用哪些iface进行收发流;

2-conf.L2listen对各个iface进行监听

3-subprocess.Popen来调用tShark.exe启动抓包,也可以调用ping.exe构造ping包

4-sendp发送二层报文,send发送三层报文

5-sniff嗅探iface上的指定报文,可以有过滤条件

6-停止wireshark抓包

7-close关闭对iface的监听

讨论:

没有尝试采用sr1、srp来进行收发包。

整个过程相对比较清晰,而且步骤是成对出现,方便记忆。

sniff嗅探时,会丢掉iface前面出现的部分报文,这个问题可能是没有执行好监听和启动抓包导致。

没有对网卡的具体性能标准作出说明,可能需要摸着石头过河,如果发现网卡有不合适测试的,需要立即切换到仪表来测试。

#! usr/bin/env python# -*- coding:utf-8 -*-import osimport sysimport reimport structimport stringfrom scapy.all import *import subprocessconf.use_pcap = True '''cmdpythonfrom scapy.all import *ls(Ether())ls(IP())ls(ICMP())send(IP(dst='1.2.3.4')/ICMP())sendp(Raw("zhongxing"), iface='eth15', loop=1, inter=0.2, verbose=False)设置 inter 参数来设置发送相邻两个包直接的时间间隔设置 timeout 参数来设置等待应答的超时时间设置 retry 参数来设置重试次数。'''print u"实现网卡发包"target = []for i in range(1,len(sys.argv)):  m = sys.argv[i].split('=')  if m[0]=='-t':    target.append(m[1])  if m[0]=='-ip':    target.append(m[1])  if m[0]=='-mac':    target.append(m[1])print 'test -- ',targetprintprint u'获取网卡的iface'eth_local = []a = repr(conf.route).split('/n')for x in a:  b = []  b = x.split(' ')  for y in b:    if re.search('eth', y):      eth_local.append(y)print u'去重复'c = []c.append(eth_local[0])for i in range(0,len(eth_local),1):  m = 0  for j in range(0,len(c),1):    if c[j] == eth_local[i]:      m += 1  if m==0:    c.append(eth_local[i])print c #['eth15', 'eth21', 'eth17']print u'创建二层报文'src_mac = '00:00:11:11:22:22'dst_mac = '00:00:22:22:11:11'dst_ip = '1.2.3.4'src_ip = '5.6.7.8'src_port = 1234dst_port = 5678##ls()##ls(IP())##IP().show()##lsc()pack_ip = IP(dst=dst_ip, src=src_ip, proto=1)##ls(ICMP())##ls(UDP())pack_icmp = ICMP(type=8)##ls(Ether())pack_ether = Ether(dst=dst_mac, src=src_mac, type=0x0800)info = Raw('zhongxing')t = str(pack_ether/pack_ip/pack_icmp/info)s = Ether(t)print u'待发送的报文为:',s.summaryeth = c[1]print u'发送的网卡iface为 %s/n' % ethprint u'---------开始监听 - 发送icmp - 嗅探icmp - 关闭监听----------'print u'---------开始监听-------------'L2socket = conf.L2listenlisten_socket = L2socket(type=ETH_P_ALL, iface=eth)print listen_socketprint conf.L2listen####启动抓包##cmd='C:/Program Files (x86)/Wireshark/tShark.exe'##card_id = str(1)##cap_file = str('H:/python/test.pcap')##args = [cmd,"-i "+card_id,"-w",cap_file]##print "*DEBUG*",args##p=subprocess.Popen(args)print u'---------sendp()函数调用----------'sendp(s,iface=eth, verbose=False)##print u'---------srp()函数调用----------'##sr 函数是 Scapy 的核心,这个函数返回两个列表,##第一个列表是收到应答的包和其对应的应答,##第二个列表是未收到应答的包,##通常,我们需要调用别的函数来使得这两个返回值更易于阅读,##help(srp)##p = srp(s,iface=c[1], verbose=False)##print p.show()print u'---------嗅探、过滤、保存pcap、读取pcap----------'##print sniff.__doc__##pkts = sniff(iface = 'eth15',filter = 'icmp',count = 3, prn=lambda x: x.summary())ip = '172.10.0.1'subprocess.Popen(["ping.exe", ip]) #提供给sniff##Ether / IP / ICMP 172.10.1.124 > 172.10.0.1 echo-request 0 / Raw##Ether / IP / ICMP 172.10.0.1 > 172.10.1.124 echo-reply 0 / Raw##Ether / IP / ICMP 172.10.1.124 > 172.10.0.1 echo-request 0 / Raw##listen_socket1 = L2socket(listen_socket)##pkts = sniff(iface = eth,filter = 'icmp',count = 20, timeout = 10, L2socket=listen_socket)pkts = sniff(iface = eth, filter = 'icmp', count = 20, timeout = 10) try:  if 0 < len(pkts):    print u'---------嗅探到报文----------'    ##pkts[0].show()    wrpcap('demo.pcap',pkts)    read_pkts = rdpcap('demo.pcap')    print read_pkts[0]    print u'---------------输出base64编码格式的数据---------------'    export_object(str(pkts[0]))    print u'---------------转换为base64编码格式的数据---------------'    newPkt = import_object('eNprYAqN+Q8GGp/TOCfN5GBwZWDwc/nCwNAgOItrDRdjLxD/Z+gEQitpgwvijAIMjAxgoODmAYLO/    /m7ebq6ubs7+ri6uAa5+YNrf2dHREaiEgbGQUQ8AnjEcMQ==')    print newPkt    s = Ether(newPkt)    print u'待发送的报文为:',s.summary    sendp(s,iface=eth, verbose=False)  else:    print u'---------没有嗅探到报文----------'except:  passfinally:  print u'---------关闭监听-------------'  listen_socket.close()

以上这篇python 的 scapy库,实现网卡收发包的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表