Sha256: b5fde2560d4ab4b0fbc908c72f5bb5e2d1b75acf670f3d79b46fc56ecc730d6b

Contents?: true

Size: 1.58 KB

Versions: 1

Compression:

Stored size: 1.58 KB

Contents

require "tcpdump_parser/version"
require 'open3'

TCPDUMP_REGEX = /
  (?<date_time>\d+-\d+-\d+\s\d+:\d+:\d+)\.\d+ # date et heure
  \s+
  (?<mac_addr_from>[a-zA-Z0-9]{2}(?::[a-zA-Z0-9]{2}){5}) # mac-address
  \s+
  >
  \s+
  (?<mac_addr_to>[a-zA-Z0-9]{2}(?::[a-zA-Z0-9]{2}){5}) # mac-address
  .* # ethertype IP4
  length\s(?<length_1>\d+):
  (?:\s+
  (?<ip_addr_from>\d+(?:\.\d*){3}|[a-zA-Z0-9]{1,4}(?::[a-zA-Z0-9]{0,4})+)\.\d+ # ip adress
  \s+
  >
  \s+
  (?<ip_addr_to>\d+(?:\.\d*){3}|[a-zA-Z0-9]{1,4}(?::[a-zA-Z0-9]{0,4})+)\.\d+ # ip adress
  .* # ethertype IP4
  length\s(?<length_2>\d+))?
/x

module TcpdumpParser
  def TcpdumpParser.parse_line(line)
    res = TCPDUMP_REGEX.match(line.chomp)

    if res.nil?
      return nil
    end

    date_time = DateTime.strptime(res[:date_time], "%Y-%m-%d %H:%M:%S").to_time
    utc_date_time = date_time - date_time.utc_offset

    return {
      date_time: utc_date_time,
      mac_addr_to: res[:mac_addr_to].upcase,
      ip_addr_to: res[:ip_addr_to],
      mac_addr_from: res[:mac_addr_from].upcase,
      ip_addr_from: res[:ip_addr_from],
      length: res[:length_1].to_i
    }  
  end

  def TcpdumpParser.listen_to(interface, tcp_dump_path=nil, use_sudo=true)
    tcp_dump_path = "tcpdump" if tcp_dump_path.nil?
    
    args = []
    args << "sudo" if use_sudo
    args << tcp_dump_path
    args << "-i" << interface << "-n" << "-e" << "-t" << "4"
    
    stdin, stdout, stderr = Open3.popen3(*args)

    while line = stdout.gets
      if not yield(parse_line(line))
        break
      end
    end
    
    stdin.close
    stdout.close
    stderr.close
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
tcpdump_parser-1.0 lib/tcpdump_parser.rb