Method: Inspec::Resources::LinuxPorts#parse_netstat_line

Defined in:
lib/resources/port.rb

#parse_netstat_line(line) ⇒ Object



476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
# File 'lib/resources/port.rb', line 476

def parse_netstat_line(line)
  # parse each line
  # 1 - Proto, 2 - Recv-Q, 3 - Send-Q, 4 - Local Address, 5 - Foreign Address, 6 - State, 7 - User, 8 - Inode, 9 - PID/Program name
  # * UDP lines have an empty State column and the Busybox variant lacks
  # the User and Inode columns.
  reg =  /^(?<proto>\S+)\s+(\S+)\s+(\S+)\s+(?<local_addr>\S+)\s+(?<foreign_addr>\S+)\s+(\S+)?\s+((\S+)\s+(\S+)\s+)?(?<pid_prog>\S+)/
  parsed = reg.match(line)

  return {} if parsed.nil? || line.match(/^proto/i)

  # parse ip4 and ip6 addresses
  protocol = parsed[:proto].downcase

  # detect protocol if not provided
  protocol += '6' if parsed[:local_addr].count(':') > 1 && %w{tcp udp}.include?(protocol)

  # extract host and port information
  host, port = parse_net_address(parsed[:local_addr], protocol)
  return {} if host.nil?

  # extract PID
  process = parsed[:pid_prog].split('/')
  pid = process[0]
  pid = pid.to_i if pid =~ /^\d+$/
  process = process[1]

  {
    'port'     => port,
    'address'  => host,
    'protocol' => protocol,
    'process'  => process,
    'pid'      => pid,
  }
end