inspec/lib/resources/wmi.rb

76 lines
2.2 KiB
Ruby
Raw Normal View History

2016-03-01 20:01:52 +00:00
# encoding: utf-8
# author: Christoph Hartmann
# author: Dominik Richter
require 'utils/object_traversal'
2016-03-18 22:23:22 +00:00
module Inspec::Resources
2016-03-19 17:50:32 +00:00
# This resource simplifies the access to wmi
# on CLI you would use:
# WMIC /NAMESPACE:\\root\rsop\computer PATH RSOP_SecuritySettingNumeric WHERE "KeyName = 'MinimumPasswordAge' And precedence=1" GET Setting
# We use Get-WmiObject via Powershell to retrieve all values.
2016-03-18 22:23:22 +00:00
class WMI < Inspec.resource(1)
name 'wmi'
desc 'request wmi information'
example "
describe wmi('RSOP_SecuritySettingNumeric', {
namespace: 'root\\rsop\\computer',
filter: 'KeyName = \'MinimumPasswordAge\' And precedence=1'
}) do
its('Setting') { should eq true }
end
"
2016-03-01 20:01:52 +00:00
2016-03-18 22:23:22 +00:00
include ObjectTraverser
attr_accessor :content
2016-03-19 17:50:32 +00:00
2016-03-18 22:23:22 +00:00
def initialize(wmiclass, opts = {})
2016-03-19 17:50:32 +00:00
# verify that this resource is only supported on Windows
return skip_resource 'The `windows_feature` resource is not supported on your OS.' unless inspec.os.windows?
2016-03-18 22:23:22 +00:00
@wmiclass = wmiclass
@wminamespace = opts[:namespace]
@wmifilter = opts[:filter]
end
2016-03-01 20:01:52 +00:00
2016-03-18 22:23:22 +00:00
# returns nil, if not existant or value
def method_missing(*keys)
2016-03-19 17:50:32 +00:00
# catch behavior of rspec its implementation
2016-03-18 22:23:22 +00:00
# @see https://github.com/rspec/rspec-its/blob/master/lib/rspec/its.rb#L110
keys.shift if keys.is_a?(Array) && keys[0] == :[]
2016-03-19 17:50:32 +00:00
# map all symbols to strings
keys = keys.map(&:to_s) if keys.is_a?(Array)
2016-03-18 22:23:22 +00:00
value(keys)
end
2016-03-01 20:01:52 +00:00
2016-03-18 22:23:22 +00:00
def value(key)
extract_value(key, info)
end
2016-03-01 20:01:52 +00:00
2016-03-18 22:23:22 +00:00
def info
return @content if defined?(@content)
@content = {}
2016-03-19 17:50:32 +00:00
# we should abort execution, if wmi class is not given or wmi resource is
# executed on a non-windows system
return @content if @wmiclass.nil?
2016-03-18 22:23:22 +00:00
# optional params
cmd_namespace = "-namespace #{@wminamespace}" unless @wminamespace.nil?
cmd_filter = "-filter \"#{@wmifilter}\"" unless @wmifilter.nil?
2016-03-18 22:23:22 +00:00
# run wmi command
cmd = inspec.command("Get-WmiObject -class #{@wmiclass} #{cmd_namespace} #{cmd_filter} | ConvertTo-Json")
@content = JSON.parse(cmd.stdout)
2016-03-19 17:50:32 +00:00
rescue JSON::ParserError => _e
2016-03-18 22:23:22 +00:00
@content
end
2016-03-18 22:23:22 +00:00
def to_s
"WMI #{@wmiclass} where #{@wmifilter}"
end
end
2016-03-01 20:01:52 +00:00
end