How to use file method of Inspec Package

Best Inspec_ruby code snippet using Inspec.file

helpers.rb

Source:helpers.rb Github

copy

Full Screen

1# frozen_string_literal: true2# Copyright 2020 Peter Mudd3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15#16# Author: Peter Mudd (https://github.com/muddman)17# C:\salt\salt-call.bat --config-dir=C:\Users\vagrant\AppData\Local\Temp\kitchen\etc\salt state.show_highstate18# --out yaml |Select-String -Pattern "__sls__", "__env__", "- run", "- order:" -NotMatch19# GENERAL HELPERS20require 'inspec/resources/registry_key'21def server?22 if defined?(@cache_server)23 Inspec::Log.debug('(server?) using cache @cache_server')24 return @cache_server25 end26 begin27 @cache_server = inspec.registry_key('HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion')['ProductName'].match? 'Server'28 rescue StandardError => e29 Inspec::Log.error('(server?) rescue:' + e.message)30 return false31 end32 Inspec::Log.debug('(server?) ending')33 @cache_server34end35# SALTSTACK HELPERS36require 'safe_yaml'37require 'train'38require 'timeout'39require "inspec/log"40require 'json'41require 'os'42SafeYAML::OPTIONS[:default_mode] = :safe43# https://www.inspec.io/docs/reference/inputs/44def set_input_pillar_default45 input('pillar', value: get_pillar_default, type: 'hash', description: 'SaltStack Pillar Data')46end47def get_pillar48 if defined?(@cache_pillar)49 Inspec::Log.debug('(get_pillar?) returning cached value')50 return @cache_pillar51 end52 @cache_pillar = try_get_pillar53 if defined?(@cache_pillar)54 Inspec::Log.debug('(get_pillar) success, got pillar. Cached result.')55 @cache_pillar56 end57end58def try_get_pillar59 # require 'pp'; pp input('pillar').diagnostic_string;60 # REMOVE THIS61 # return get_pillar_from_inspec_pillar_file62 unless input('pillar').is_a?(Inspec::Input::NO_VALUE_SET)63 Inspec::Log.debug('Got pillar from kitchen input.')64 puts 'INFO: Got pillar from kitchen input.'65 return input('pillar')66 end67 # pillar_from_minion = get_pillar_from_minion68 pillar_from_minion = ingest_from_minion('yaml', 'c:\salt\salt-call.bat --config-dir=C:\Users\vagrant\AppData\Local\Temp\kitchen\etc\salt pillar.items --retcode-passthrough | Select-String -Pattern "----------" -NotMatch')69 unless !defined?(pillar_from_minion) || pillar_from_minion == []70 Inspec::Log.debug('Got pillar from the target minion using WinRM.')71 puts 'INFO: Got pillar from the target minion using WinRM.'72 return pillar_from_minion['local']73 end74 pillar_from_inspec_pillar_file = get_pillar_from_inspec_pillar_file75 unless !defined?(pillar_from_inspec_pillar_file) || pillar_from_inspec_pillar_file == []76 Inspec::Log.debug('Got pillar from the inspec pillar file.')77 puts 'INFO: Got pillar from the inspec pillar file.'78 return pillar_from_inspec_pillar_file79 end80 raise 'Unable to get pillar from input, minion or local inspec pillar file.'81end82def get_pillar_from_inspec_pillar_file83 if defined?(@cache_pillar_from_inspec_pillar_file)84 Inspec::Log.debug('[get_pillar_from_inspec_pillar_file] returning cached value')85 return @cache_pillar_from_inspec_pillar_file86 end87 pillar_file = ENV['INSPEC_TEST_SALT_PILLAR'] || 'pillar.example'88 begin89 @cache_pillar_from_inspec_pillar_file = YAML.safe_load(File.read(pillar_file)) if File.exist?(pillar_file)90 rescue StandardError => e91 Inspec::Log.warn('[get_pillar_from_inspec_pillar_file] ' + e.message)92 return []93 end94 if defined?(@cache_pillar_from_inspec_pillar_file)95 Inspec::Log.debug('[get_pillar_from_inspec_pillar_file] success, got the pillar from the inspec file. Cached result.')96 @cache_pillar_from_inspec_pillar_file97 end98end99def ingest_from_minion(type, ps_cmd, max_retries = 20, sec_timeout = 10)100 # grep "WinRM address:" $(ls -t .kitchen/logs/*.log | head -n2 | tail -n1) | sed 's/^.*: //'101 # Test port open: nc -z -w1 localhost 55985;echo $?102 # nc -z -w1 $(sed -n -e 's/^.*WinRM address: //p' $(ls -t .kitchen/logs/*.log | sed -n '2p') | cut -f1 -d:) $(sed -n -e 's/^.*WinRM address: //p' $(ls -t .kitchen/logs/*.log | sed -n '2p') | cut -f2 -d:); echo $? 103 # cd .kitchen/kitchen-vagrant/{instance name}; vagrant winrm --command whoami104 # cd .kitchen/kitchen-vagrant/{instance name}; vagrant winrm-config105 # cmd ="nc -z -w1 $(sed -n -e 's/^.*WinRM address: //p' $(ls -t .kitchen/logs/*.log | sed -n '2p') | cut -f1 -d:) $(sed -n -e 's/^.*WinRM address: //p' $(ls -t .kitchen/logs/*.log | sed -n '2p') | cut -f2 -d:); echo $?"106 retries ||= 0107 Inspec::Log.debug("Ingesting #{type} content using `#{ps_cmd}` with timout of #{sec_timeout} and a max of #{max_retries} retries.")108 # require 'pry'; binding.pry109 begin110 # https://www.rubydoc.info/gems/train/0.14.1/Train%2FTransports%2FLocal%2FConnection:run_command111 # Train.Plugins.Transport.Connection train.connection.run_command112 Timeout.timeout(sec_timeout) do113 @my_result = JSON.parse(backend::backend.run_command(ps_cmd).stdout) if type == 'json'114 @my_result =YAML.safe_load(backend::backend.run_command(ps_cmd).stdout) if type == 'yaml'115 end116 rescue => e117 Inspec::Log.debug("`#{e.message}`, target may be rebooting after highstate. Remaining retries: #{max_retries - retries}")118 puts("`#{e.message}`, target may be rebooting after highstate. Remaining retries: #{max_retries - retries}")119 if (retries += 1) < max_retries120 retry121 else122 begin123 backend::backend.run_command('whoami').stdout124 rescue => e125 msg = "Unable to get whoami from backend::backend.run_command: #{e.message}"126 puts(msg)127 Inspec::Log.debug(msg)128 end129 if OS.windows?130 pwsh_cmd = '$test_path=".kitchen/kitchen-vagrant/$(Get-ChildItem -Path .kitchen/logs/*.log | Where-Object {$_.Name -ne "kitchen.log"} | Sort-Object -Property @{Expression = {$_.LastWriteTime}; Descending = $True} | Select-Object -Property BaseName -First 1 -expandproperty BaseName)"; Set-Location -Path $test_path; $test_vagrantfile = "$test_path/Vagrantfile"; Set-Content -Path $test_vagrantfile -Value (get-content -Path $test_vagrantfile | Select-String -Pattern "vagrant_vb_guest.rb" -NotMatch); Set-Location -Path $test_path; vagrant winrm'131 cmd = "powershell -command '#{pwsh_cmd}'"132 else133 cmd = "cd .kitchen/kitchen-vagrant/$(ls -t .kitchen/logs/*.log | grep -v .kitchen/logs/kitchen.log | head -n1 | cut -f3 -d/ | awk -F. '{print $1}'); vagrant winrm"134 end135 if system( cmd )136 puts('Successfully connected via `vagrant winrm`')137 Inspec::Log.debug('Successfully connected via `vagrant winrm`')138 else139 msg = 'Failed to connect via `vagrant winrm`'140 puts(msg)141 Inspec::Log.debug(msg)142 # abort msg143 end144 end145 end146 if defined?(@my_result)147 Inspec::Log.debug("Ingested #{type} content successfully from minion using Train.Plugins.Transport.Connection.")148 @my_result149 else150 Inspec::Log.debug('Failed to get content from minion using Train.Plugins.Transport.Connection.')151 puts "WARNING: Failed to get content from minion using Train.Plugins.Transport.Connection."152 []153 end154end155# pp get_mystates_from_highstate('module','chocolatey','bootstrap')156# pp get_mystates_from_highstate('module','user','current')157# pp get_mystates_from_highstate('state','system','hostname')158def get_highstate_from_minion159 if defined?(@cache_highstate_from_minion)160 Inspec::Log.debug('Returning cached @cache_highstate_from_minion.')161 return @cache_highstate_from_minion162 end163 # ingest_from_minion('yaml', 'C:\salt\salt-call.bat --config-dir=C:\Users\vagrant\AppData\Local\Temp\kitchen\etc\salt state.show_highstate --out yaml |Select-String -Pattern "__sls__", "__env__", "- run", "- order:" -NotMatch')164 highstate_from_minion = ingest_from_minion('json', 'C:\salt\salt-call.bat --config-dir=C:\Users\vagrant\AppData\Local\Temp\kitchen\etc\salt state.show_highstate --out json')165 if highstate_from_minion != []166 Inspec::Log.debug('Saving highstate to cache @cache_highstate_from_minion.')167 @cache_highstate_from_minion = highstate_from_minion['local']168 @cache_highstate_from_minion169 else170 Inspec::Log.error('Failed to get highstate.')171 abort 'Failed to get highstate.'172 end173end174# Example modules175# "windows.module.status.uptime"=>176# {"module"=>177# [{"status.uptime"=>[{"human_readable"=>true}]},178# {"require"=>["windows.module.user.current"]},179# "run",180# {"order"=>10004}],181# "__sls__"=>"windows.modules",182# "__env__"=>"base"},183# "chocolatey.bootstrap"=>184# {"module"=>185# [{"chocolatey.bootstrap"=>nil},186# {"unless"=>"where.exe chocolatey"},187# "run",188# {"order"=>10010}],189# "__sls__"=>"windows.system.packages.chocolatey.bootstrap",190# "__env__"=>"base"},191# Example State192# {"windows.state.system.computer_desc.description"=>193# {"system"=>194# [{"name"=>"Saltstack Computer Description"},195# {"require"=>["windows.state.system.hostname.saltstack1"]},196# "computer_desc",197# {"order"=>10000}],198# "__sls__"=>"windows.states",199# "__env__"=>"base"},200def get_mystates_from_highstate(type, find_state, find_function)201 found_states = {}202 highstate = get_highstate_from_minion203 Inspec::Log.debug("Getting #{type}s for #{find_state}.#{find_function}.")204 # puts "highstate class: " + highstate.class.to_s205 # pp highstate206 highstate.each do |state_id, state|207 # puts "state class: " + state.class.to_s208 Inspec::Log.debug("Checking #{state_id} from highstate.")209 case type210 when 'state'211 if state.key?(find_state) && state[find_state].include?(find_function)212 Inspec::Log.debug("Found state #{find_state}.#{find_function} from highstate.")213 found_states[state_id] = state214 end215 when 'module'216 if state.key?('module')217 check_module = state['module'][0]218 # pp check_module219 if check_module.key?("#{find_state}.#{find_function}") || (check_module.key?(find_state) && check_module[find_state][0] == find_function)220 Inspec::Log.debug("Found module #{find_state}.#{find_function} from highstate.")221 found_states[state_id] = state222 end223 end224 end225 end226 if found_states != {}227 Inspec::Log.debug("Got #{type}s for #{find_state}.#{find_function}.")228 # pp found_states229 found_states230 else231 Inspec::Log.error("Unable to get #{type}'s for #{find_state}.#{find_function}'")232 end233end234# example: get_saltstack_package_full_name('7zip') = '7-Zip'235def get_saltstack_package_full_name(package)236 # pillar = YAML.safe_load(File.read('test/salt/pillar/windows.sls'))237 url = 'https://raw.githubusercontent.com/saltstack/salt-winrepo-ng/master/'238 files = [package + '.sls', package + '/init.sls']239 # example: package = "7zip"=>{"version"=>"18.06.00.0", "refresh_minion_env_path"=>false}240 saltstack_package_full_name = files.find do |checkme|241 ps = "$f = (((Get-ChildItem -Path $env:LOCALAPPDATA -Filter 'salt-winrepo-ng' -Recurse -Directory).Fullname[0]) + '\\#{checkme.sub('/', '\\')}'); if (Test-Path $f -PathType Leaf) {Get-Content -Path $f}"242 begin243 file = (open(url + checkme) & :read)244 rescue245 begin246 file = (powershell(ps).stdout)247 rescue248 next249 end250 end251 unless file.nil? || file.empty?252 candidate = file.match(/full_name: '([\S]+).*'/).captures[0]253 end254 break candidate unless candidate.nil?255 end256 Inspec::Log.debug('[get_saltstack_package_full_name] found candidate: ' + saltstack_package_full_name)257 saltstack_package_full_name258end...

Full Screen

Full Screen

reporter.rb

Source:reporter.rb Github

copy

Full Screen

1require_relative "mixin/erb_helpers"2require_relative "mixin/file_resolver"3require "erb" unless defined? ERB4module InspecPlugins::FlexReporter5 class Reporter < Inspec::Reporters::Json6 include InspecPlugins::FlexReporter::ErbHelpers7 include InspecPlugins::FlexReporter::FileResolver8 ENV_PREFIX = "INSPEC_REPORTER_FLEX_".freeze9 attr_writer :config, :env, :inspec_config, :logger, :template_contents10 # Render report11 def render12 template = ERB.new(template_contents)13 # Use JSON Reporter base's `report` to have pre-processed data14 mushy_report = Hashie::Mash.new(report)15 # Eeease of use here16 platform = mushy_report.platform17 profiles = mushy_report.profiles18 statistics = mushy_report.statistics19 version = mushy_report.version20 # Some pass/fail information21 test_results = profiles.map(&:controls).flatten.map(&:results).flatten.map(&:status)22 passed_tests = test_results.select { |text| text == "passed" }.count23 failed_tests = test_results.count - passed_tests24 percent_pass = 100.0 * passed_tests / test_results.count25 percent_fail = 100.0 - percent_pass26 # Detailed OS27 platform_arch = runner.backend.backend.os.arch28 platform_name = runner.backend.backend.os.title29 # Allow template-based settings30 template_config = config.fetch("template_config", {})31 # ... also can use all InSpec resources via "inspec_resource.NAME.PROPERTY"32 output(template.result(binding))33 end34 # Return Constraints.35 #36 # @return [String] Always "~> 0.0"37 def self.run_data_schema_constraints38 "~> 0.0"39 end40 private41 # Read contents of requested template.42 #43 # @return [String] ERB Template44 # @raise [IOError]45 def template_contents46 @template_contents ||= File.read full_path(config["template_file"])47 end48 # Initialize configuration with defaults and Plugin config.49 #50 # @return [Hash] Configuration data after merge51 def config52 @config unless @config.nil?53 # Defaults54 @config = {55 "template_file" => "templates/flex.erb",56 }57 @config.merge! inspec_config.fetch_plugin_config("inspec-reporter-flex")58 @config.merge! config_environment59 logger.debug format("Configuration: %<config>s", config: @config)60 @config61 end62 # Allow (top-level) setting overrides from environment.63 #64 # @return [Hash] Configuration data from environment65 def config_environment66 env_reporter = env.select { |var, _| var.start_with?(ENV_PREFIX) }67 env_reporter.transform_keys { |key| key.delete_prefix(ENV_PREFIX).downcase }68 end69 # Return environment variables....

Full Screen

Full Screen

erb_helpers.rb

Source:erb_helpers.rb Github

copy

Full Screen

1module InspecPlugins::FlexReporter2 module ErbHelpers3 # Return approximate time of the scan4 #5 # @return [DateTime] Timestamp of the first scan in the profile6 def scan_time7 scan_time = report[:profiles].detect { |p| p[:controls].detect { |c| c[:results].detect { |r| !r.empty? } } }.dig(:controls, 0, :results, 0, :start_time)8 DateTime.strptime(scan_time)9 end10 # Execute a remote command.11 #12 # @param [String] cmd Command to execute13 # @return [Train::Extras::CommandResult] Command result (.stdout/.stderr/.exit_status)14 def remote_command(cmd)15 runner.backend.backend.run_command(cmd)16 end17 # Retrieve remote file contents.18 #19 # @param [String] remote_file Path to the remote file20 # @return [String] Contents of the file21 def remote_file_content(remote_file)22 runner.backend.backend.file(remote_file).content23 end24 # Allow access to all InSpec resources from the report.25 #26 # @return [Inspec::Backend] The InSpec backend27 def inspec_resource28 runner.backend29 end30 # Return InSpec OS resource results.31 #32 # @return [Class] Look into documentation for properties (.arch/.family/.name/...)33 # @see https://github.com/inspec/inspec/blob/master/lib/inspec/resources/os.rb34 def os35 runner.backend.os36 end37 # Return InSpec SysInfo resource results.38 #39 # @return [Class] Look into documentation for properteis (.domain/.fqdn/.hostname/.ip_address/.model/...)40 # @see https://github.com/inspec/inspec/blob/master/lib/inspec/resources/sys_info.rb41 def sys_info42 runner.backend.sys_info43 end44 # Return if all results of a control have passed/skipped/waived.45 #46 # @param [Hash] control Data of a control run47 # @return [Boolean] If all passed checks48 def control_passed?(control)49 control[:results].any? { |result| result[:status] == "failed" }50 end51 # Map InSpec status to cleartext52 #53 # @param [String] inspec_status One of the valid InSpec result status.54 # @return [Strint] "ok"/"not ok" depending on status55 def status_to_pass(inspec_status)56 case inspec_status57 when "passed", "skipped", "waived"58 "ok"59 else60 "not ok"61 end62 end63 # Map InSpec severity (0..1) to CVSS scale (none-low-medium-high-critical)64 #65 # @param [Float] inspec_severity Severity from the profile66 # @return [String] One of the scale values67 # @see https://www.first.org/cvss/specification-document#Qualitative-Severity-Rating-Scale68 def impact_to_severity(inspec_severity)69 case inspec_severity70 when 0.0...0.171 "none"72 when 0.1...0.473 "low"74 when 0.4...0.775 "medium"76 when 0.7...0.977 "high"78 when 0.9..1.079 "critical"...

Full Screen

Full Screen

file

Using AI Code Generation

copy

Full Screen

1describe file('/etc/passwd') do2 it { should exist }3describe file('/etc/passwd') do4 it { should exist }5describe file('/etc/passwd') do6 it { should exist }7describe file('/etc/passwd') do8 it { should exist }9describe file('/etc/passwd') do10 it { should exist }11describe file('/etc/passwd') do12 it { should exist }13describe file('/etc/passwd') do14 it { should exist }15describe file('/etc/passwd') do16 it { should exist }17describe file('/etc/passwd') do18 it { should exist }19describe file('/etc/passwd') do20 it { should exist }21describe file('/etc/passwd') do22 it { should exist }23describe file('/etc/passwd') do24 it { should exist }25describe file('/etc/passwd') do26 it { should exist }27describe file('/etc/passwd') do28 it { should exist }29describe file('/etc/passwd') do

Full Screen

Full Screen

file

Using AI Code Generation

copy

Full Screen

1describe file('/etc/passwd') do2 it { should exist }3 its('mode') { should cmp '0644' }

Full Screen

Full Screen

file

Using AI Code Generation

copy

Full Screen

1describe file('/etc/hosts') do2 it { should exist }3 its('content') { should match(/

Full Screen

Full Screen

file

Using AI Code Generation

copy

Full Screen

1describe file('/etc/passwd') do2 it { should exist }3 its('type') { should cmp 'file' }

Full Screen

Full Screen

file

Using AI Code Generation

copy

Full Screen

1describe file('/tmp/1.rb') do2 it { should exist }3 it { should be_file }

Full Screen

Full Screen

file

Using AI Code Generation

copy

Full Screen

1describe file('/etc/passwd') do2 its('content') { should match(/root:x:0:0:root/) }3describe file('/etc/passwd') do4 its('content') { should match(/root:x:0:0:root/) }5describe file('/etc/passwd') do6 its('content') { should match(/root:x:0:0:root/) }7describe file('/etc/passwd') do8 its('content') { should match(/root:x:0:0:root/) }9describe file('/etc/passwd') do10 its('content') { should match(/root:x:0:0:root/) }11describe file('/etc/passwd') do12 its('content') { should match(/root:x:0:0:root/) }13describe file('/etc/passwd') do14 its('content') { should match(/root:x:0:0:root/) }15describe file('/etc/passwd') do16 its('content') { should match(/root:x:0:0:root/) }17describe file('/etc/passwd') do18 its('content') { should match(/root:x:0:0:root/) }19describe file('/etc/passwd') do20 its('content') { should match(/root:x:0:0:root

Full Screen

Full Screen

file

Using AI Code Generation

copy

Full Screen

1 it { should be_file }2 it { should be_owned_by 'root' }3 it { should be_file }4 it { should be_owned_by 'root' }

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Inspec_ruby automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful