Module: Inspec::Utils::SolarisNetstatParser

Included in:
Resources::SolarisPorts
Defined in:
lib/inspec/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


137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/inspec/utils/parser.rb', line 137

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 do |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 do |i|
        info[names[i]] = port[i] if i != 0
      end

      ports.push(info)
    end
  end
  ports
end