#! /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/^[ \t]*//g' | grep -E -v ^'0x' | grep -E 'cksum|seq'
cmd1 = ['tcpdump', '-i', 'any', '-vv', '-XX', '-n', '-B', '4096','-s', '0']
cmd2 = ['sed', 's/^[ \t]*//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