最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python如何實(shí)時(shí)獲取tcpdump輸出

 更新時(shí)間:2020年09月16日 09:49:55   作者:文淵  
這篇文章主要介紹了python如何實(shí)時(shí)獲取tcpdump輸出,幫助大家更好的理解和使用python,感興趣的朋友可以了解下

一、背景

  今天有個小需求,要確認(rèn)客戶端有沒有往服務(wù)端發(fā)送udp包,但為了減輕工作量,不想每次到機(jī)器上手動執(zhí)行tcpdump抓包命令。
  于是就寫了個腳本來釋放人力。

二、代碼實(shí)現(xiàn)

  整個腳本我還加了一些其他功能:時(shí)間戳、發(fā)送端IP提取,數(shù)據(jù)包分析,數(shù)據(jù)持久化等。這里都先去掉,僅記錄下簡單的實(shí)時(shí)獲取tcpdump輸出功能。
  代碼如下:

# -*- coding: utf-8 -*-
# !/usr/bin/env python

# sudo tcpdump -tt -l -nn -c 5 -i enp4s0 udp port 514 or 51414

import subprocess

cmd = ['sudo', 'tcpdump', '-tt', '-l', '-nn', '-c', '5', '-i', 'enp4s0', 'udp', 'port', '514', 'or', '51414']
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)

while True:
  line = proc.stdout.readline()
  line = line.strip()
  if not line:
    print('tcpdump finished...')
    break
  print(line)

  輸出如下(實(shí)時(shí)):

wenyuanblog@localhost:/home/test/script# python tcpdump_udp.py 
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on enp4s0, link-type EN10MB (Ethernet), capture size 262144 bytes
1499774951.124178 IP 192.168.10.210.41974 > 192.168.10.251.514: UDP, length 139
1499774953.125664 IP 192.168.10.210.54995 > 192.168.10.251.51414: UDP, length 139
1499774956.128498 IP 192.168.10.210.56748 > 192.168.10.251.514: UDP, length 139
1499774958.129918 IP 192.168.10.210.53883 > 192.168.10.251.51414: UDP, length 139
1499774961.132921 IP 192.168.10.210.58803 > 192.168.10.251.514: UDP, length 139
5 packets captured
6 packets received by filter
0 packets dropped by kernel
tcpdump finished...

  以上代碼相當(dāng)于手動執(zhí)行了 sudo tcpdump -tt -l -nn -c 5 -i enp4s0 udp port 514 or 51414 這條命令。
  注意參數(shù)-l很重要(行顯)。

三、代碼實(shí)現(xiàn)(更新)

  上面的代碼能實(shí)現(xiàn)tcpdump的功能,但是有一個問題:沒有做超時(shí)保護(hù)。即當(dāng)程序執(zhí)行時(shí)間過長時(shí)kill該進(jìn)程(這里使用ctrl+c的方式)。
  要實(shí)現(xiàn)這個功能有很多種方案,例如定時(shí)器+多線程等,這里僅演示一種方案,代碼如下:

# -*- coding: utf-8 -*-
# !/usr/bin/env python

# sudo tcpdump -tt -l -nn -c 50 -i enp4s0 udp port 514 or 51414

import subprocess
import signal
import time
import os
import re
import json


class CmdServer:

  def __init__(self, cmd, timeout=120):
    '''
    :param cmd: 執(zhí)行命令(列表形式)
    :param timeout: 任務(wù)超時(shí)時(shí)間(seconds,進(jìn)程運(yùn)行超過該時(shí)間,kill該進(jìn)程)
    :param taskname: 任務(wù)名稱(根據(jù)該任務(wù)名稱記錄命令輸出信息)
    '''
    self.cmd = cmd
    self.timeout = timeout
    self.base_path = reduce(lambda x, y: os.path.dirname(x), range(1), os.path.abspath(__file__))
    self.output_path = os.path.join(self.base_path, 'data.json')
    self.udp_flow_list = []
    self.begin_time = int(time.time())

  # 執(zhí)行tcpdump任務(wù)
  def run(self):
    if os.path.exists(self.output_path):
      with open(self.output_path, 'r') as f:
        self.udp_flow_list = json.load(f)

    proc = subprocess.Popen(self.cmd, stdout=subprocess.PIPE)
    stdout = ''

    while proc.poll() == None:
      current_time = int(time.time())
      if current_time - self.begin_time >= self.timeout:
        print('tcpdump timeout...')
        proc.send_signal(signal.SIGINT)
        stdout = proc.stdout.read()

    if proc.poll() is not None and not stdout:
      print('tcpdump finished...')
      stdout = proc.stdout.read()

    stdout_list = stdout.split('\n')
    if stdout_list:
      self._merge_data(stdout_list)
      self._save_data()

  # 數(shù)據(jù)合并(新增/更新)
  def _merge_data(self, stdout_list):
    for line in stdout_list:
      line = line.strip()
      if not line:
        continue
      timestamp = int(float(line.split('IP')[0].strip())) * 1000
      # 源
      src_ip_port_list = re.findall(r'IP(.+?)>', line)
      if not src_ip_port_list:
        continue
      src_ip_port_str = src_ip_port_list[0].strip()
      src_ip = '.'.join(src_ip_port_str.split('.')[0:4])
      # 目的
      dst_ip_port_list = re.findall(r'>(.+?):', line)
      if not dst_ip_port_list:
        continue
      dst_ip_port_str = dst_ip_port_list[0].strip()
      dst_port = dst_ip_port_str.split('.')[-1]

      # 新增/更新latest_timestamp
      src_item = filter(lambda x: src_ip == x['src_ip'], self.udp_flow_list)
      if src_item:
        src_item[0]['dst_port'] = dst_port
        src_item[0]['latest_timestamp'] = timestamp
      else:
        self.udp_flow_list.append(dict(
          src_ip=src_ip,
          dst_port=dst_port,
          latest_timestamp=timestamp
        ))

  # 保存數(shù)據(jù)
  def _save_data(self):
    # 寫入文件
    with open(self.output_path, 'w') as f:
      json.dump(self.udp_flow_list, f, encoding="utf-8", ensure_ascii=False)


if __name__ == '__main__':
  cmd = ['sudo', 'tcpdump', '-tt', '-l', '-nn', '-c', '5', '-i', 'enp4s0', 'udp', 'port', '514', 'or', '51414']
  cmd_server = CmdServer(cmd, 10)
  cmd_server.run()

四、總結(jié)

  比較簡單,僅僅是記錄下。

以上就是python如何實(shí)時(shí)獲取tcpdump輸出的詳細(xì)內(nèi)容,更多關(guān)于python獲取tcpdump輸出的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Python3數(shù)字求和的實(shí)例

    Python3數(shù)字求和的實(shí)例

    在本篇文章中小編給大家整理了關(guān)于Python3 min()函數(shù)的一些用法和相關(guān)知識點(diǎn),需要的朋友們學(xué)習(xí)下。
    2019-02-02
  • python email smtplib模塊發(fā)送郵件代碼實(shí)例

    python email smtplib模塊發(fā)送郵件代碼實(shí)例

    本篇文章給大家分享了python email smtplib模塊發(fā)送郵件的相關(guān)代碼分享,有需要的朋友參考學(xué)習(xí)下。
    2018-04-04
  • python抓取需要掃微信登陸頁面

    python抓取需要掃微信登陸頁面

    這篇文章主要介紹了python抓取需要掃微信登陸頁面的相關(guān)知識,非常不錯,具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-04-04
  • python如何修改PYTHONPATH環(huán)境變量

    python如何修改PYTHONPATH環(huán)境變量

    這篇文章主要介紹了python如何修改PYTHONPATH環(huán)境變量問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-08-08
  • opencv 閾值分割的具體使用

    opencv 閾值分割的具體使用

    這篇文章主要介紹了opencv 閾值分割的具體使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07
  • 使用python繪制人人網(wǎng)好友關(guān)系圖示例

    使用python繪制人人網(wǎng)好友關(guān)系圖示例

    這篇文章主要介紹了使用python繪制人人網(wǎng)好友關(guān)系圖示例,需要的朋友可以參考下
    2014-04-04
  • Python Pygame實(shí)現(xiàn)俄羅斯方塊

    Python Pygame實(shí)現(xiàn)俄羅斯方塊

    這篇文章主要為大家詳細(xì)介紹了Python Pygame實(shí)現(xiàn)俄羅斯方塊,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-02-02
  • Python selenium爬取微信公眾號文章代碼詳解

    Python selenium爬取微信公眾號文章代碼詳解

    這篇文章主要介紹了Python selenium爬取微信公眾號歷史文章代碼詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-08-08
  • Python  pandas中的shift位移操作方法

    Python  pandas中的shift位移操作方法

    shift()?函數(shù)是?Pandas?中用于移動或偏移數(shù)據(jù)的重要工具,它可以處理時(shí)間序列數(shù)據(jù)、計(jì)算數(shù)據(jù)差值以及進(jìn)行數(shù)據(jù)預(yù)處理,本文介紹Python  pandas中的shift位移操作方法,感興趣的朋友跟隨小編一起看看吧
    2024-03-03
  • Python+redis通過限流保護(hù)高并發(fā)系統(tǒng)

    Python+redis通過限流保護(hù)高并發(fā)系統(tǒng)

    這篇文章主要介紹了Python+redis通過限流保護(hù)高并發(fā)系統(tǒng),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-04-04

最新評論

小金县| 阿拉尔市| 丰台区| 荔波县| 罗平县| 广元市| 信宜市| 芒康县| 永胜县| 九龙坡区| 乌兰县| 鄱阳县| 怀柔区| 扶风县| 兰考县| 平顶山市| 北安市| 三原县| 汝阳县| 西城区| 南澳县| 襄城县| 丘北县| 海门市| 禄丰县| 化德县| 綦江县| 三江| 渭南市| 信丰县| 铜梁县| 固阳县| 十堰市| 武定县| 西城区| 旌德县| 喜德县| 宽城| 准格尔旗| 荃湾区| 怀仁县|