我在某种程度上是一个Python新手,但我已经接受了一个小的个人项目来自学更多。基本上,我正在编写一个使用套接字和impacket的数据包嗅探器。但是,我遇到了一个特殊的问题:将报头和数据包的输出组合到一个变量中(我想的是一个字典,但它不喜欢……)这样我就可以简单地搜索出一个特定的部分源IP的IP报头(即,前两个八位字节)。或者会有一种更有效的方法来处理这个问题?任何帮助都是非常感谢的。:-)
编辑:当我尝试字典的时候,我正在做
ip_dict = { header: packet }但是,我得到的输出类似于:
{<impacket.ImpactPacket.IP instance at 0x02563440>: <impacket.ImpactPacket.Data instance at 0x02563530>}而不是所述IP报头和数据的实际输出。
HOST = socket.gethostbyname(socket.gethostname())
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
s.bind((HOST, 0))
while True:
# Include IP headers
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
# receive all packages
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
# receive a packet
packet = s.recvfrom(42028)[0]
# look at IP info
h_decode = ImpactDecoder.IPDecoder()
header = h_decode.decode(packet)
# disabled promiscuous mode
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
decoder = ImpactDecoder.DataDecoder()
packet = decoder.decode(packet)
print header
print packet
time.sleep(1)发布于 2012-08-29 03:58:37
字典是键/值对的集合。当你使用
ip_dict = { header: packet }您告诉它使用header实例作为键,packet实例作为值来构建一个字典,这就是它所做的:
{<impacket.ImpactPacket.IP instance at 0x02563440>: <impacket.ImpactPacket.Data instance at 0x02563530>}如果你想从这些实例中提取一些东西,你必须自己提取它。例如,尽管我以前从未使用过impacket库,但对象中似乎有很多方法。例如,隐藏实数和数据,并将其替换为无意义
In [25]: z
Out[25]: <impacket.ImpactPacket.IP instance at 0xb6151fac>
In [26]: z.[here I hit TAB in the IPython interpreter]
z.add_option z.get_ip_offmask z.set_bytes_from_string
z.auto_checksum z.get_ip_p z.set_checksum_from_data
z.calculate_checksum z.get_ip_rf z.set_ip_address
z.child z.get_ip_src z.set_ip_df
z.compute_checksum z.get_ip_sum z.set_ip_dst
z.contains z.get_ip_tos z.set_ip_hl
z.ethertype z.get_ip_ttl z.set_ip_id
z.fragment_by_list z.get_ip_v z.set_ip_len
z.fragment_by_size z.get_long z.set_ip_mf
z.get_buffer_as_string z.get_packet z.set_ip_off
z.get_byte z.get_pseudo_header z.set_ip_offmask
z.get_bytes z.get_size z.set_ip_p
z.get_data_as_string z.get_word z.set_ip_rf
z.get_header_size z.is_BSD z.set_ip_src
z.get_ip_address z.list_as_hex z.set_ip_sum
z.get_ip_df z.load_header z.set_ip_tos
z.get_ip_dst z.normalize_checksum z.set_ip_ttl
z.get_ip_hl z.packet_printable z.set_ip_v
z.get_ip_id z.parent z.set_long
z.get_ip_len z.protocol z.set_parent
z.get_ip_mf z.set_byte z.set_word
z.get_ip_off z.set_bytes
In [26]: z.get_ip_src()
Out[26]: '1.2.3.4' # fake
In [27]: z.get_ip_dst()
Out[27]: '5.6.7.8' # fake
In [29]: z.get_data_as_string()
Out[29]: '\x00abcde' # fake我不知道其中一半的方法是做什么的,或者哪些方法是重要的,但你可以很容易地用你喜欢的任何东西来构建一本字典:
In [31]: {(z.get_ip_src(), z.get_ip_dst()): z.get_bytes()}
Out[31]:
{('1.2.3.4',
'5.6.7.8'): array('B', [1,2,3,4,5,6,7,8])} # fake或者组合来自IPDecoder和DataDecoder的比特,诸如此类。问题的关键不在于Python字典,而在于impacket库的数据结构,以及您想要从中提取哪些信息。文档可能会描述如何获取您所需的内容。
https://stackoverflow.com/questions/12162563
复制相似问题