python实现linux下抓包并存库功能

yipeiwu_com6年前Python基础

最近项目需要抓包功能,并且抓包后要对数据包进行存库并分析。抓包想使用tcpdump来完成,但是tcpdump抓包之后只能保存为文件,我需要将其保存到数据库。想来想去shell脚本似乎不太好实现,于是用了比较热门的python来实现。不得不说,python丰富的第三方库确实是很强大,下面是具体的功能代码。

from apscheduler.scheduler import Scheduler
import os
import sys
import time
import MySQLdb
import ConfigParser
import Logger

def main():

  logger = Logger.Logger(logname='flowstat.log', loglevel=1, logger='flowstat').getlog()

  try:
    cf = ConfigParser.ConfigParser()
    cf.read('./flowstat.conf')

    filterNet1 = cf.get('packet', 'filterNet1')
    filterNet2 = cf.get('packet', 'filterNet2')
    packetFile = cf.get('packet', 'packetFile')

    db_host = cf.get('db', 'host')
    db_user = cf.get('db', 'user')
    db_passwd = cf.get('db', 'passwd')
    db_dbname = cf.get('db', 'dbname')

    conn = MySQLdb.connect(host=db_host, user=db_user, passwd=db_passwd, db=db_dbname, port=3306)

    os.system('nohup ./capturePacket.sh ' + filterNet1 + ' ' + filterNet2 + ' ' + packetFile + ' &')
  except Exception, e:
    logger.error(e)
    sys.exit(1)


  sched = Scheduler(daemonic = False)
  @sched.cron_schedule(day_of_week='0-4', hour='*', minute='0-59', second='*/60')
  def packagestat_job():
    logger.debug('stat package' + ' ' + time.strftime("%Y-%m-%d %H:%M:%S"))
    try:
      fos = open(packetFile, 'r+')
      lines = fos.readlines()
      values = []
      for line in lines:
        arr = line.split(',')
        if len(arr) > 4:
          values.append((arr[0].strip(), arr[2].strip(), arr[3].strip(), arr[4].strip()))

      if len(values) > 0:
        cur = conn.cursor()
        cur.executemany('insert into tbpk_packet(TimesMacs, LengthIps, Seq, Ack) values(%s,%s,%s,%s)', values)
        conn.commit()
        cur.close()

      fos.truncate(0)
      fos.close()
    except Exception, e3:
      Logger.error(e3)


  sched.start()

  while 1:
    time.sleep(60)

  conn.close()

if __name__ == '__main__':
  main()

shell脚本
#!/bin/sh
tcpdump -i eth0 -l >> *.txt

上面的功能涉及到了文件操作,数据库操作,定时任务等几个功能点。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python3实现生成随机密码的方法

本文实例讲述了Python3实现生成随机密码的方法,在Python程序设计中有着广泛的实用价值。具体方法如下: 本文实例主要实现创建8位随机密码(大小写字母+数字),采用Python3生...

tensorflow中next_batch的具体使用

本文介绍了tensorflow中next_batch的具体使用,分享给大家,具体如下: 此处给出了几种不同的next_batch方法,该文章只是做出代码片段的解释,以备以后查看:...

matplotlib绘制符合论文要求的图片实例(必看篇)

matplotlib绘制符合论文要求的图片实例(必看篇)

最近需要将实验数据画图出来,由于使用python进行实验,自然使用到了matplotlib来作图。 下面的代码可以作为画图的模板代码,代码中有详细注释,可根据需要进行更改。 # -*...

pandas删除指定行详解

pandas删除指定行详解

在处理pandas的DataFrame中,如果想像excel那样筛选,只要其中的某一行或者几行,可以使用isin()方法来实现,只需要将需要的行值以列表方式传入即可,还可传入字典,进行指...

基于Python实现一个简单的银行转账操作

基于Python实现一个简单的银行转账操作

前言 在进行一个应用系统的开发过程中,从上到下一般需要四个构件:客户端-业务逻辑层-数据访问层-数据库,其中数据访问层是一个底层、核心的技术。而且在实际开发中,数据库的操作也就是说数据访...