简体   繁体   English

python3中的数据包嗅探器

[英]Packet sniffer in python3

So browsing the web, there is a lot of information about packet sniffers. 因此,浏览网页有很多关于数据包嗅探器的信息。 However, all of the code or libraries seem to only be for python2. 但是,所有代码或库似乎只适用于python2。 I am trying to make a simple packet sniffer in python3 for testing purposes. 我试图在python3中创建一个简单的数据包嗅探器用于测试目的。

I grabbed the code from http://www.binarytides.com/python-packet-sniffer-code-linux/ and tried to convert it to python3. 我从http://www.binarytides.com/python-packet-sniffer-code-linux/抓取代码并尝试将其转换为python3。 However, there is a problem with the way python2 and python3 handles the struct.unpack function. 但是,python2和python3处理struct.unpack函数的方式存在问题。

Here is a snippet of their code (slightly modified for python3) that grabs the ethernet header and prints out the MAC address. 这是他们的代码片段(稍微修改为python3),它抓取以太网头并打印出MAC地址。

 def eth_addr (a) : a = str(a) # added because TypeError occurs with ord() without it b = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (ord(a[0]) , ord(a[1]) , ord(a[2]), ord(a[3]), ord(a[4]) , ord(a[5])) return b #create a AF_PACKET type raw socket (thats basically packet level) #define ETH_P_ALL 0x0003 /* Every packet (be careful!!!) */ try: s = socket.socket( socket.AF_PACKET , socket.SOCK_RAW , socket.ntohs(0x0003)) except socket.error as msg: msg = list(msg) print('Socket could not be created. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]) sys.exit() # receive a packet while True: packet = s.recvfrom(65565) #packet string from tuple packet = packet[0] #parse ethernet header eth_length = 14 eth_header = packet[:eth_length] eth = unpack('!6s6sH' , eth_header) eth_protocol = socket.ntohs(eth[2]) print('Destination MAC : ' + eth_addr(packet[0:6]) + ' Source MAC : ' + eth_addr(packet[6:12]) + ' Protocol : ' + str(eth_protocol)) 

Inserting print statements reveals the unpacking of the header, there seems to be a difference between python2 and python3. 插入print语句会显示标题的解包,python2和python3之间似乎有区别。 Python3 still has the data encoded as binary data. Python3仍然将数据编码为二进制数据。 But if I try and decode the data, it throws an error about incorrect "utf-8" formatting. 但是,如果我尝试解码数据,它会抛出错误的“utf-8”格式错误。

How can I get the MAC address to format properly in python3? 如何在python3中正确格式化MAC地址?

Thanks 谢谢

Remove the a = str(a) line and the ord() calls: 删除a = str(a)行和ord()调用:

def eth_addr (a) :
  b = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (a[0] , a[1] , a[2], a[3], a[4] , a[5])
  return b

In Python 3, bytes objects produce integers when subscripted, so you do not need to call ord() on them. 在Python 3中, bytes对象在下标时产生整数,因此您不需要在它们上调用ord() Casting a bytes object to str() like that is incorrect, because it will try to parse it as UTF-8. bytes对象str()转换为str()是不正确的,因为它会尝试将其解析为UTF-8。 This is unsuccessful because you do not have UTF-8, you have random binary garbage. 这是不成功的,因为你没有UTF-8,你有随机二进制垃圾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM