Module: SolarisNetstatParser

Included in:
SolarisPorts
Defined in:
lib/utils/parser.rb

Instance Method Summary collapse

Instance Method Details

#parse_netstat(content) ⇒ Object

takes this as a input and parses the values UDP: IPv4

Local Address        Remote Address      State

——————– ——————– ———-

*.*                                 Unbound


102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/utils/parser.rb', line 102

def parse_netstat(content) # rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity, Metrics/AbcSize
  return [] if content.nil? || content.empty?

  protocol = nil
  column_widths = nil
  ports = []
  cache_name_line = nil

  content.each_line { |line|
    # find header, its delimiter
    if line =~ /TCP:|UDP:|SCTP:/
      # get protocol
      protocol = line.split(':')[0].chomp.strip.downcase

      # determine version tcp, tcp6, udp, udp6
      proto_version = line.split(':')[1].chomp.strip
      protocol += '6' if proto_version == 'IPv6'

      # reset names cache
      column_widths = nil
      cache_name_line = nil
      names = nil
    # calulate width of a column based on the horizontal line
    elsif line =~ /^[- ]+$/
      column_widths = columns(line)
    # parse header values from line
    elsif column_widths.nil? && !line.nil?
      # we do not know the width at this point of time, therefore we need to cache
      cache_name_line = line
    # content line
    elsif !column_widths.nil? && !line.nil? && !line.chomp.empty?
      # default row
      port = split_columns(column_widths, line).to_a.map { |v| v.chomp.strip }

      # parse the header names
      # TODO: names should be optional
      names = split_columns(column_widths, cache_name_line).to_a.map { |v| v.chomp.strip.downcase.tr(' ', '-').gsub(/[^\w-]/, '_') }
      info = {
        'protocol' => protocol.downcase,
      }

      # generate hash for each line and use the names as keys
      names.each_index { |i|
        info[names[i]] = port[i] if i != 0
      }

      ports.push(info)
    end
  }
  ports
end