Python中的简单原始数据包嗅探器

时间:2014-07-10 01:11:36

标签: python packet-sniffers sniffing

首先,我是python的初学者。我开发了一个简单的原始数据包嗅探器,利用在第2层运行的PF_PACKET接口。

嗅探器只是弄清楚以下内容...... - 以太网标头(源 - 目的地 - 协议) - IP标头(源IP - 目标IP) - TCP标头(源端口 - 目标端口)

这是我到目前为止编写的代码......

#!/usr/bin/env python
import struct
import socket
import binascii

rawSocket=socket.socket(socket.PF_PACKET,socket.SOCK_RAW,socket.htons(0x0800))
#ifconfig eth0 promisc up
receivedPacket=rawSocket.recv(2048)

#Ethernet Header...
ethernetHeader=receivedPacket[0][0:14]
ethrheader=struct.unpack("!6s6s2s",ethernetHeader)
destinationIP= binascii.hexlify(ethrheader[0])
sourceIP= binascii.hexlify(ethrheader[1])
protocol= binascii.hexlify(ethrheader[2])
print "Destinatiom: " + destinationIP
print "Souce: " + sourceIP
print "Protocol: "+ protocol

#IP Header... 
ipHeader=receivedPacket[0][14:34]
ipHdr=struct.unpack("!12s4s4s",ipHeader)
destinationIP=socket.inet_ntoa(ipHdr[2])
print "Source IP: " +sourceIP
print "Destination IP: "+destinationIP

#TCP Header...
tcpHeader=receivedPacket[0][34:54]
tcpHdr=struct.unpack("!2s2s16s",tcpHeader)
sourcePort=socket.inet_ntoa(tcpHdr[0])
destinationPort=socket.inet_ntoa(tcpHdr[1])
print "Source Port: " + sourcePort
print "Destination Port: " + destinationPort

我似乎遇到了以太网头部分和unpack方法中的问题,我无法弄清楚。在此先感谢:)

2 个答案:

答案 0 :(得分:2)

你的字符串切片语句中有一个额外的[0]

ethernetHeader=receivedPacket[0][0:14]

应该只是

ethernetHeader=receivedPacket[0:14]

错误告诉您struct.unpack需要一个长度为14的字符串。如果您打印了传递给它的字符串,您可能会看到它只有长度= 1。这是一个例子:

>>> s = 'this is a test'
>>> s[0]
't'
>>> s[0][0:4]
't'
>>> s[0:4]
'this'

答案 1 :(得分:2)

#!/usr/bin/env python
import struct
import sys,os
import socket
import binascii

rawSocket=socket.socket(socket.PF_PACKET,socket.SOCK_RAW,socket.htons(0x0800))
#ifconfig eth0 promisc up
receivedPacket=rawSocket.recv(2048)

#Ethernet Header...
ethernetHeader=receivedPacket[0:14]
ethrheader=struct.unpack("!6s6s2s",ethernetHeader)
destinationIP= binascii.hexlify(ethrheader[0])
sourceIP= binascii.hexlify(ethrheader[1])
protocol= binascii.hexlify(ethrheader[2])

print "Destination: " + destinationIP
print "Source: " + sourceIP
print "Protocol: "+ protocol

#IP Header... 
ipHeader=receivedPacket[14:34]
ipHdr=struct.unpack("!12s4s4s",ipHeader)
destinationIP=socket.inet_ntoa(ipHdr[2])
sourceIP=socket.inet_ntoa(ipHdr[1])
print "Source IP: " +sourceIP
print "Destination IP: "+destinationIP

#TCP Header...
tcpHeader=receivedPacket[34:54]
tcpHdr=struct.unpack("!2s2s16s",tcpHeader)
sourcePort=socket.inet_ntoa(tcpHdr[0])
destinationPort=socket.inet_ntoa(tcpHdr[1])
print "Source Port: " + sourcePort
print "Destination Port: " + destinationPort