• 基于Python2.7开发的tcpdump采集程序


    #! /usr/bin/python  
    #coding:utf-8
    '''
    # -------------------------------------------------------------------------------
    # Filename:    tcpdump.py
    # Revision:    0.1
    # Date:        2018/04/03
    # Author:      stivee
    # Email:       lxs@xdja.com
    # Description: 采集网口数据,python2.7 ,epoll
    # Notes:       启动:nohup python tcpdump.py > /dev/null 2>&1 &
    # -------------------------------------------------------------------------------
    ''' 
    
    from select import *
    import subprocess, os, time, fcntl, shutil
    def tcpdump():  
        
        # tcpdump -i any -vv -XX -n -B 4096 -s 0 | sed 's/^[ 	]*//g' | grep -E -v ^'0x' | grep -E 'cksum|seq' 
        cmd1 = ['tcpdump', '-i', 'any', '-vv', '-XX', '-n', '-B', '4096','-s', '0'] 
        cmd2 = ['sed', 's/^[ 	]*//g'] 
        cmd3 = ['grep', '--line-buffered',  '-a', '-E', '-v', '^0x'] 
        cmd4 = ['grep', '--line-buffered',  '-a', '-E', 'cksum|seq'] 
        pipe1 = subprocess.Popen(cmd1, stdout=subprocess.PIPE)  
        pipe2 = subprocess.Popen(cmd2, stdout=subprocess.PIPE, stdin=pipe1.stdout)
        pipe3 = subprocess.Popen(cmd3, stdout=subprocess.PIPE, stdin=pipe2.stdout)
        pipe = subprocess.Popen(cmd4, stdout=subprocess.PIPE, stdin=pipe3.stdout)
        flags = fcntl.fcntl(pipe.stdout.fileno(), fcntl.F_GETFL)
        fcntl.fcntl(pipe.stdout.fileno(), fcntl.F_SETFL, (flags | os.O_NDELAY | os.O_NONBLOCK))
        return pipe
    
    def poll_tcpdump(proc):
        txt = None
        while True:
            epoll_instance = epoll()
            epoll_instance.register(proc.stdout.fileno(),EPOLLIN|EPOLLET)
            epoll_list = epoll_instance.poll(1)
        
            if not len(epoll_list):
                break
            try:
                for line in iter(proc.stdout.readline, ""):
                    if txt is None:
                        txt = ''
                    txt += time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + " " + line
    				
            except Exception as e:
                print e
                pass
            break
        return txt
    
    proc = tcpdump()
        
    while True:
        text = poll_tcpdump(proc)
        filesize = os.path.getsize('/home/logs/tcpdump.log')
        if filesize > 1024000000:
            shutil.move('/home/logs/tcpdump.log','/home/logs/tcpdump.logbak')
        if text:
            with open("/home/logs/tcpdump.log","a") as f:
                f.write(text)
                #print ">>>>",text
    

      

  • 相关阅读:
    mysql脚本导入导出
    centos6.9关闭防火墙
    hdfs 架构
    MySQL JOIN的使用
    六种方式,教你在SpringBoot初始化时搞点事情!
    mybatis快速入门
    有了Swagger2,再也不用为写Api文档头疼了
    kafka查看Topic列表及消费状态等常用命令
    @RequestMapping注解
    寻找写代码感觉(三)之使用 Spring Boot 编写接口
  • 原文地址:https://www.cnblogs.com/idvcn/p/8716066.html
Copyright © 2020-2023  润新知