Class: Rex::Text::Table

Inherits:
Object
  • Object
show all
Defined in:
lib/rex/text/table.rb

Overview

Prints text in a tablized format. Pretty lame at the moment, but whatever.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Table

Initializes a text table instance using the supplied properties. The Table class supports the following hash attributes:

Header

The string to display as a heading above the table. If none is specified, no header will be displayed.

HeaderIndent

The amount of space to indent the header. The default is zero.

Columns

The array of columns that will exist within the table.

Rows

The array of rows that will exist.

Width

The maximum width of the table in characters.

Indent

The number of characters to indent the table.

CellPad

The number of characters to put between each horizontal cell.

Prefix

The text to prefix before the table.

Postfix

The text to affix to the end of the table.

Sortindex

The column to sort the table on, -1 disables sorting.



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/rex/text/table.rb', line 59

def initialize(opts = {})
  self.header   = opts['Header']
  self.headeri  = opts['HeaderIndent'] || 0
  self.columns  = opts['Columns'] || []
  # updated below if we got a "Rows" option
  self.rows     = []

  self.width    = opts['Width']   || 80
  self.indent   = opts['Indent']  || 0
  self.cellpad  = opts['CellPad'] || 2
  self.prefix   = opts['Prefix']  || ''
  self.postfix  = opts['Postfix'] || ''
  self.colprops = []
  self.scterm   = /#{opts['SearchTerm']}/mi if opts['SearchTerm']

  self.sort_index  = opts['SortIndex'] || 0
  self.sort_order  = opts['SortOrder'] || :forward

  # Default column properties
  self.columns.length.times { |idx|
    self.colprops[idx] = {}
    self.colprops[idx]['MaxWidth'] = self.columns[idx].length
  }

  # ensure all our internal state gets updated with the given rows by
  # using add_row instead of just adding them to self.rows.  See #3825.
  opts['Rows'].each { |row| add_row(row) } if opts['Rows']

  # Merge in options
  if (opts['ColProps'])
    opts['ColProps'].each_key { |col|
      idx = self.columns.index(col)

      if (idx)
        self.colprops[idx].merge!(opts['ColProps'][col])
      end
    }
  end

end

Instance Attribute Details

#cellpadObject

:nodoc:



304
305
306
# File 'lib/rex/text/table.rb', line 304

def cellpad
  @cellpad
end

#colpropsObject

:nodoc:



303
304
305
# File 'lib/rex/text/table.rb', line 303

def colprops
  @colprops
end

#columnsObject

:nodoc:



303
304
305
# File 'lib/rex/text/table.rb', line 303

def columns
  @columns
end

#headerObject

:nodoc:



302
303
304
# File 'lib/rex/text/table.rb', line 302

def header
  @header
end

#headeriObject

:nodoc:



302
303
304
# File 'lib/rex/text/table.rb', line 302

def headeri
  @headeri
end

#indentObject

:nodoc:



304
305
306
# File 'lib/rex/text/table.rb', line 304

def indent
  @indent
end

#postfixObject

:nodoc:



305
306
307
# File 'lib/rex/text/table.rb', line 305

def postfix
  @postfix
end

#prefixObject

:nodoc:



305
306
307
# File 'lib/rex/text/table.rb', line 305

def prefix
  @prefix
end

#rowsObject

:nodoc:



303
304
305
# File 'lib/rex/text/table.rb', line 303

def rows
  @rows
end

#sctermObject

:nodoc:



306
307
308
# File 'lib/rex/text/table.rb', line 306

def scterm
  @scterm
end

#sort_indexObject

:nodoc:



306
307
308
# File 'lib/rex/text/table.rb', line 306

def sort_index
  @sort_index
end

#sort_orderObject

:nodoc:



306
307
308
# File 'lib/rex/text/table.rb', line 306

def sort_order
  @sort_order
end

#widthObject

:nodoc:



304
305
306
# File 'lib/rex/text/table.rb', line 304

def width
  @width
end

Class Method Details

.new_from_csv(csv) ⇒ Object

Build table from CSV dump



253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/rex/text/table.rb', line 253

def self.new_from_csv(csv)
  # Read in or keep data, get CSV or die
  if csv.is_a?(String)
    csv = File.file?(csv) ? CSV.read(csv) : CSV.parse(csv)
  end
  # Adjust for skew
  if csv.first == ["Keys", "Values"]
    csv.shift # drop marker
    cols = []
    rows = []
    csv.each do |row|
      cols << row.shift
      rows << row
    end
    tbl = self.new('Columns' => cols)
    rows.in_groups_of(cols.count) {|r| tbl << r.flatten}
  else
    tbl = self.new('Columns' => csv.shift)
    while !csv.empty? do
      tbl << csv.shift
    end
  end
  return tbl
end

Instance Method Details

#<<(fields) ⇒ Object

Adds a row using the supplied fields.



163
164
165
# File 'lib/rex/text/table.rb', line 163

def <<(fields)
  add_row(fields)
end

#[](*col_names) ⇒ Object



278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/rex/text/table.rb', line 278

def [](*col_names)
  tbl = self.class.new('Indent' => self.indent,
                       'Header' => self.header,
                       'Columns' => col_names)
  indexes = []

  col_names.each do |col_name|
    index = self.columns.index(col_name)
    raise RuntimeError, "Invalid column name #{col_name}" if index.nil?
    indexes << index
  end

  self.rows.each do |old_row|
    new_row = []
    indexes.map {|i| new_row << old_row[i]}
    tbl << new_row
  end

  return tbl
end

#add_hrObject

Adds a horizontal line.



217
218
219
# File 'lib/rex/text/table.rb', line 217

def add_hr
  rows << '__hr__'
end

#add_row(fields = []) ⇒ Object

Adds a row with the supplied fields.



170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/rex/text/table.rb', line 170

def add_row(fields = [])
  if fields.length != self.columns.length
    raise RuntimeError, 'Invalid number of columns!'
  end
  fields.each_with_index { |field, idx|
    # Remove whitespace and ensure String format
    field = field.to_s.strip
    if (colprops[idx]['MaxWidth'] < field.to_s.length)
      old = colprops[idx]['MaxWidth']
      colprops[idx]['MaxWidth'] = field.to_s.length
    end
  }

  rows << fields
end

#drop_leftObject

Returns new sub-table with headers and rows maching column names submitted

Flips table 90 degrees left



227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/rex/text/table.rb', line 227

def drop_left
  tbl = self.class.new(
    'Columns' => Array.new(self.rows.count+1,'  '),
    'Header' => self.header,
    'Indent' => self.indent)
  (self.columns.count+1).times do |ti|
    row = self.rows.map {|r| r[ti]}.unshift(self.columns[ti]).flatten
    # insert our col|row break. kind of hackish
    row[1] = "| #{row[1]}" unless row.all? {|e| e.nil? || e.empty?}
    tbl << row
  end
  return tbl
end

#header_to_sObject

Returns the header string.



143
144
145
146
147
148
149
150
151
# File 'lib/rex/text/table.rb', line 143

def header_to_s # :nodoc:
  if (header)
    pad = " " * headeri

    return pad + header + "\n" + pad + "=" * header.length + "\n\n"
  end

  return ''
end

Prints the contents of the table.



156
157
158
# File 'lib/rex/text/table.rb', line 156

def print
  puts to_s
end

#sort_rows(index = sort_index, order = sort_order) ⇒ Object

Sorts the rows based on the supplied index of sub-arrays If the supplied index is an IPv4 address, handle it differently, but avoid actually resolving domain names.



191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/rex/text/table.rb', line 191

def sort_rows(index = sort_index, order = sort_order)
  return if index == -1
  return unless rows
  rows.sort! do |a,b|
    if a[index].nil?
      cmp = -1
    elsif b[index].nil?
      cmp = 1
    elsif valid_ip?(a[index]) and valid_ip?(b[index])
      cmp = IPAddr.new(a[index]) <=> IPAddr.new(b[index])
    elsif a[index] =~ /^[0-9]+$/ and b[index] =~ /^[0-9]+$/
      cmp = a[index].to_i <=> b[index].to_i
    elsif a[index].kind_of?(IPAddr) && a[index].kind_of?(IPAddr) && a[index].ipv6? && b[index].ipv4?
      cmp = 1
    elsif a[index].kind_of?(IPAddr) && b[index].kind_of?(IPAddr) && a[index].ipv4? && b[index].ipv6?
      cmp = -1
    else
      cmp = a[index] <=> b[index] # assumes otherwise comparable.
    end
    order == :forward ? cmp : -cmp
  end
end

#to_csvObject

Converts table contents to a csv



126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/rex/text/table.rb', line 126

def to_csv
  str = ''
  str << ( columns.join(",") + "\n" )
  rows.each { |row|
    next if is_hr(row) || !row_visible(row)
    str << ( row.map{|x|
      x = x.to_s
      x.gsub(/[\r\n]/, ' ').gsub(/\s+/, ' ').gsub('"', '""')
    }.map{|x| "\"#{x}\"" }.join(",") + "\n" )
  }
  str
end

#to_sObject

Converts table contents to a string.



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/rex/text/table.rb', line 103

def to_s
  str  = prefix.dup
  str << header_to_s || ''
  str << columns_to_s || ''
  str << hr_to_s || ''

  sort_rows
  rows.each { |row|
    if (is_hr(row))
      str << hr_to_s
    else
      str << row_to_s(row) if row_visible(row)
    end
  }

  str << postfix

  return str
end

#valid_ip?(value) ⇒ Boolean

Returns:

  • (Boolean)


241
242
243
244
245
246
247
248
# File 'lib/rex/text/table.rb', line 241

def valid_ip?(value)
  begin
    IPAddr.new value
    true
  rescue IPAddr::InvalidAddressError
    false
  end
end