python socket 编程 (看python黑帽编程4.1做的笔记)

原文链接python黑帽编程4.1 Sniffer嗅探器

通过 ifconfig eth1 promisc 设置网卡为混杂模式

创建socket对象、接收数据、分析数据

import o
import socket
import ctypes
#PromiscuousSocket这个类负责创建一个绑定到当前主机名绑定的网卡上的raw socket对象,并设置启动混杂模式。
class PromiscuousSocket (object):
#__init__()用来创建socket对象,并绑定到对象的s字段上
    def __init__(self):
        pass
    def __enter__(self):
        pass
    def __exit__(self,*args,**kwargs):
        pass
#sniffer创建PromiscuousSocket类实例,并使用这个实例接收和分析数据
def sniffer(count,buffersize=65565,showPort=False,showRawData=False):
    pass
#printPacket用来显示补获的内容
def printPacket(package,showPort,showRawData):
    pass
sniffer(count=10,showPort=True,showRawData=True)

def __init__(self):
    HOST=socket.gethostbyname(socket.gethostname())
    s=socket.socket(socket.AF_INET,socket.SOCKET_RAW,
    socket.IPPROTO_IP)
#socket.AF_INET---表示ipv4;socket.RAW---表示原始套接字
#setsocketopt用来对socket对象进行补充选项的设置,三个选项分别是level、选项名称、和值
    s=setsocketopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
    s.bind((HOST,0))
    #保护IP头部
        s.setsocketopt(socket.IPPROTO_IP,socket.IP_HDRINCL,1)
    #设置混杂模式
    s.ioctl(socket.SIO_RCVALL,socket.RCVALL_ON)
    self.s=s
def __enter__(self):
    return self.s
    #返回创建的socket对象
def __exit__(self,*args,**kwargs):
    self.s.ioctl(socket.SIO_RCVALL,socket.RCVALL_OFF)
    #关闭混杂模式

#接收数据包,打印基本信息
def sniffer(count,buffersize=65565,showPort=False,showRawData=False):
    with PromiscuousSocket() as s:
        for i in range(count):
            package=s.recvfrom(buffSize)
            printPacket(package,showPort,showRawData)

def printPacket(pacage,showPort,showRawData):
    dataIndex=0
    headerIndex=1
    ipAddressIndex=0
    portIndex=1
    print 'IP:',pacage[headerIndex][ipAddressIndex,end='']
    if(showPort):
        print ('Port:',pacage[headerIndex][portIndex,end='')
    if(showRawData):
        print ('data:',pacage[dataIndex])

猜你喜欢

转载自blog.csdn.net/dididisailor/article/details/53012401