Python开发【笔记】:抓包(实时分隔)

时间:2022-12-20 10:38:51

抓包

进行linux系统抓包,并且定时分隔防止文件太大

#!/usr/bin/env python
# -*- coding:utf-8 -*- import os
import sys
import logging
import threading
import time
import datetime # 工作目录
WORKSPACE = '/root/workspace'
# 间隔时间 分钟
INTERVAL = 10 def daemon():
import os
# create - fork 1
try:
pid = os.fork()
if pid > 0:
return pid
except OSError as error:
logging.error('fork #1 failed: %d (%s)' % (error.errno, error.strerror))
return -1
# it separates the son from the father
os.chdir(WORKSPACE)
os.setsid()
os.umask(0)
# create - fork 2
try:
pid = os.fork()
if pid > 0:
return pid
except OSError as error:
logging.error('fork #2 failed: %d (%s)' % (error.errno, error.strerror))
return -1
sys.stdout.flush()
sys.stderr.flush()
si = open("/dev/null", 'r')
so = open("/dev/null", 'ab')
se = open("/dev/null", 'ab', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
return 0 def tcpdump(filename):
logging.info('start')
os.system(f'tcpdump -i any -w {filename}.pcap') def run():
while True:
try:
filename = str(time.strftime('%Y-%m-%d_%H:%M', time.localtime()))
logging.info(f'tcpdump {filename}')
threading.Thread(target=tcpdump,args=(filename,)).start()
time.sleep(INTERVAL * 60)
os.system("ps -ef | grep tcpdump | awk '{print $2}' | xargs kill -9")
except Exception as e:
logging.error(e) def main():
pid = daemon()
if pid:
return pid
run() if __name__ == '__main__':
logging.basicConfig(filename="tcpdump.log", level=logging.INFO,
format="%(asctime)s [%(filename)s:%(lineno)d] %(message)s", datefmt="%m/%d/%Y %H:%M:%S [%A]")
main()