Scapy使用奇怪的Python内存

Dus*_*off 6 python mysql sqlalchemy

我写了一个脚本,通过SQLAlchemy将pcapy中的mac地址记录到mysql中,我最初使用的是直接的sqlite3,但很快意识到需要更好的东西,所以这个周末过去我重写了所有的数据库谈话以符合SQLAlchemy.一切正常,数据进入并再次出现.我虽然sessionmaker()对我来说管理DB的所有会话非常有用.

我看到有关内存消耗的奇怪事件.我启动脚本...它收集并写入所有数据库...但是每隔2-4秒我的内存消耗量会增加兆字节.目前我正在谈论的记录很少,不到100行.

脚本序列:

  1. 脚本开始
  2. SQLAlchemy将mac_addr列读入maclist [].
  3. scapy获取数据包>如果new_mac在maclist []中?

如果是真的?仅将时间戳写入时间戳列,其中mac = newmac.回到第2步.

如果是假的?然后将新的mac写入DB.清除maclist []并再次调用第2步.

1小时30分钟后,我的内存占用量为1027MB(RES)和1198MB(VIRT),在1表数据库(MySQL)中有124行.

问:这可以归功于每次从DB清理和重新填充的maclist []吗?

问:当它达到系统最大内存时会发生什么?

任何想法或建议都会非常感谢.

memory_profiler输出有问题的段,其中list []从数据库mac_addr列填充.

Line #    Mem usage    Increment   Line Contents
================================================
   123 1025.434 MiB    0.000 MiB   @profile
   124                             def sniffmgmt(p):
   125                              global __mac_reel
   126                              global _blacklist
   127 1025.434 MiB    0.000 MiB    stamgmtstypes = (0, 2, 4)
   128 1025.434 MiB    0.000 MiB    tmplist = []
   129 1025.434 MiB    0.000 MiB    matching = []
   130 1025.434 MiB    0.000 MiB    observedclients = []
   131 1025.434 MiB    0.000 MiB    tmplist = populate_observed_list()
   132 1025.477 MiB    0.043 MiB    for i in tmplist:
   133 1025.477 MiB    0.000 MiB          observedclients.append(i[0])
   134 1025.477 MiB    0.000 MiB    _mac_address = str(p.addr2)
   135 1025.477 MiB    0.000 MiB    if p.haslayer(Dot11):
   136 1025.477 MiB    0.000 MiB        if p.type == 0 and p.subtype in stamgmtstypes:
   137 1024.309 MiB   -1.168 MiB            _timestamp = atimer()
   138 1024.309 MiB    0.000 MiB            if p.info == "":
   139 1021.520 MiB   -2.789 MiB                        _SSID = "hidden"
   140                                          else:
   141 1024.309 MiB    2.789 MiB                        _SSID = p.info
   142                                      
   143 1024.309 MiB    0.000 MiB            if p.addr2 not in observedclients:
   144 1018.184 MiB   -6.125 MiB                    db_add(_mac_address, _timestamp, _SSID)
   145 1018.184 MiB    0.000 MiB                    greetings()
   146                                      else:
   147 1024.309 MiB    6.125 MiB                add_time(_mac_address, _timestamp)
   148 1024.309 MiB    0.000 MiB                observedclients = [] #clear the list
   149 1024.309 MiB    0.000 MiB                observedclients = populate_observed_list() #repopulate the list
   150 1024.309 MiB    0.000 MiB                greetings()
Run Code Online (Sandbox Code Playgroud)

您将看到observeclients是有问题的列表.

Dus*_*off 8

我设法找到了内存消耗的实际原因.它本身就是傻瓜.默认情况下,Scapy设置为存储它捕获的所有数据包.但你可以禁用它.

禁用:

sniff(iface=interface, prn=sniffmgmt, store=0)
Run Code Online (Sandbox Code Playgroud)

启用:

sniff(iface=interface, prn=sniffmgmt, store=1)
Run Code Online (Sandbox Code Playgroud)

感谢BitBucket Ticket