Python 在不应该的时候附加到列表

标签 python python-2.7 scapy

为了好玩,我正在制作一个简单的脚本来嗅探网络并记录 IP 地址及其 mac 地址。

from scapy.all import *
import sys
import os

regestry = [['192.168.0.1','E8:DE:27:55:17:F4']]

def islocal(str):
    lst = str.split('.')
    if lst[0] == '192' and lst[1] == '168': 
        return True
    else:
        return False

def packatalize(packet):
    try:    
        dst = packet["IP"].dst
        if islocal(dst):
            var = False
            for reg in regestry:
                if dst not in reg:
                    print 'not in reg'
                    var = True
                elif dst in reg:
                    print 'in reg'
                    var = False
                    pass
            if var == True:
                print 'appending'
                regestry.append([dst,packet.dst])
                print regestry
                var = False

            else:
                pass    
        else:
            print 'not local'
            pass 
    except Exception as e: 
        print str(e)

sniff(prn=packatalize)

sys.exit()

这完成了我想要它做的事情,但出于某种原因,它一遍又一遍地附加这些 IP 和 MAC 注册表,即使它们已经存在。

最佳答案

For fun I'm making a simple script that sniffs on a network and logs the IP addresses and their mac addresses.

那么我可以建议您为您的特定应用程序使用适当的数据结构吗?不过,dict 似乎足够好,因为它的键是唯一的,即为现有 IP 重新更新 mac 地址,将更新注册表中的 mac 地址,而不是创建新条目.

>>> registry = {}
>>> registry['192.168.0.1'] = 'E8:DE:27:55:17:F4'

使用字典:

>>> registry['192.168.0.2'] = 'E8:DE:27:55:17:F1'
>>> for ip, mac in registry.iteritems():
...     print ip, mac
... 
192.168.0.2 E8:DE:27:55:17:F1
192.168.0.1 E8:DE:27:55:17:F4

如果你想让你的字典保持插入顺序,请见OrderedDict

如果您想使用集合而不是用列表模拟集合

您可以使用集合(与使用自己的 Python 代码自己编写相比更不容易出错),而不是手动检查一个值是否已在列表中并且仅在不存在时才添加它

>>> registry = set()

此行创建一个集合,在您的示例中它将是“唯一”值的列表

>>> registry.add(('192.168.0.1','E8:DE:27:55:17:F4'))

如果该值尚不存在,则添加该值。

然后使用它,它与列表没有太大区别,例如

>>> registry.add(('192.168.0.2','E8:DE:27:55:17:F1'))
>>> for reg in registry:
...     print reg
... 
('192.168.0.1', 'E8:DE:27:55:17:F4')
('192.168.0.2', 'E8:DE:27:55:17:F1')

请注意,集合不维护插入顺序。

关于Python 在不应该的时候附加到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41514730/

相关文章:

python-2.7 - difflib.get_close_matches 获得分数

Python:在三引号中键入制表符和\t 之间的区别

python - 需要帮助将模块导入 PyCharm

python - scapy 嗅探功能没有捕获任何数据包

python - 在 python/scapy 中采样流量

python - 类型错误 : content() takes exactly 1 argument (0 given)

python - Python 中带有子类的单例

python - 如何在PyQt5中横向打印?

python - 如何平滑或 'relax' 由 delaunay 三角剖分产生的二维网格?

python - 如何在数据仍在传输时从 http 响应 python 获得部分结果?