1. FlyPython首页
  2. 网络安全
  3. Hacking with Python

第五课 Python网络嗅探

第五课 Python网络嗅探

第五课 Python网络嗅探

《Hacking with Python》系列课程第五课,今天我们将学习Python的一个网络数据包处理工具Scapy,用它来实现一个网络嗅探器。

主要Scapy不是爬虫Scrapy,不要搞混了。

Scapy简单介绍

从官网的自我介绍了解到,Scapy是一个强大的数据包处理程序,可以让用户发送、嗅探、解析,以及伪造网络报文,从而用来侦测、扫描和向网络发动攻击等。

  • 官网:https://scapy.net/
  • 文档:https://scapy.readthedocs.io/en/latest/
  • 中文文档:https://www.osgeo.cn/scapy/introduction.html
  • 安装:pip3  install   scapy 

Scapy抓取数据包

第五课 Python网络嗅探

from scapy.all import *
package=sniff(iface=’en0′,count=10)
wrpcap(“test.pcap”,package)

上面的代码,我们从en0上读到了10个数据包并保存到test.pcap中

package = sniff(offline='test.pcap')
print(package)

<Sniffed: TCP:0 UDP:10 ICMP:0 Other:0>

上面的代码,我们读取已经保存的数据包,并打印出来,可以看到,这是10个UDP包

package = sniff(filter=”icmp”,count=10,prn=lambda x: x.sprintf(“{IP:%IP.src%-> %IP.dst%}”))
192.168.0.100-> 192.168.0.255
192.168.0.100-> 224.0.0.251
192.168.0.100-> 239.255.255.250
192.168.0.100-> 239.255.255.250
192.168.0.100-> 239.255.255.250
192.168.0.100-> 239.255.255.250
192.168.0.100-> 239.255.255.250
192.168.0.100-> 239.255.255.250
192.168.0.100-> 239.255.255.250
192.168.0.107-> 221.178.59.140

上面的代码,我们格式化了输出,把10个数据包IP来去都显示了出来。

Scapy发送数据包

from scapy.all import *

def floodz(source,target):
    for source_p in range(100,150):
        IPlayer = IP(src=source,dst=target)
        TCPlayer = TCP(sport=source_p,dport=600)
        pkt = IPlayer/TCPlayer
        send(pkt)

source = "127.0.0.1"
target = "xxx.xxx.xxx.xxx"
floodz(source,target)

可以看到,我们使用了IPlayerTCPlayer,来构造数据包,然后发送出去。 今天的内容就到这里了,如果想深入学习Scapy,可以参考文档,明天我们将进入更核心的内容,明天见。

此系列课程代码: https://github.com/flypythoncom/Hacking-with-Python

关注我们的微信公众号,获取最新的教程信息

此图像的alt属性为空;文件名为006tNbRwly1gai7aeyheij3076076dgb.jpg


原创文章,作者:flypython,如若转载,请注明出处:http://flypython.com/video/435.html