require "tcpdump_parser/version" require 'open3' TCPDUMP_REGEX = / (?\d+-\d+-\d+\s\d+:\d+:\d+)\.\d+ # date et heure \s+ (?[a-zA-Z0-9]{2}(?::[a-zA-Z0-9]{2}){5}) # mac-address \s+ > \s+ (?[a-zA-Z0-9]{2}(?::[a-zA-Z0-9]{2}){5}) # mac-address .* # ethertype IP4 length\s(?\d+): (?:\s+ (?\d+(?:\.\d*){3}|[a-zA-Z0-9]{1,4}(?::[a-zA-Z0-9]{0,4})+)\.\d+ # ip adress \s+ > \s+ (?\d+(?:\.\d*){3}|[a-zA-Z0-9]{1,4}(?::[a-zA-Z0-9]{0,4})+)\.\d+ # ip adress .* # ethertype IP4 length\s(?\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