Class: WinrmClass

Inherits:
Object
  • Object
show all
Defined in:
lib/miq_utilities/winrm.rb

Overview

Wrapper class to interact with winrm

Instance Method Summary collapse

Instance Method Details

#winrm_run(script, host, user = nil, password = nil) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/miq_utilities/winrm.rb', line 15

def winrm_run(script, host, user = nil , password = nil)
  @logger = LoggingClass.new('WinRM')
  user ||= 'administrator'
  password ||= $evm.object.decrypt('win_password').to_s
  value = ''
  ps1 = <<~PS_SCRIPT
    #{script}
  PS_SCRIPT

  opts = {
    endpoint: "http://#{host}:5985/wsman",
    user: user.to_s,
    password: password.to_s
  }

  conn = WinRM::Connection.new(opts)

  @logger.log(level: 'info', message: "WinRM is connecting to #{opts[:endpoint]}")
  msg = ps1.to_s.gsub(password.to_s, '****')
  @logger.log(level: 'info', message: "Running PowerShell script: #{msg}")

  conn.shell(:powershell) do |shell|
    err = ''
    output = shell.run(ps1) do |stdout, stderr|
      value = stdout
      err = stderr
    end
    if output.exitcode.zero?
      @logger.log(level: 'info', message: "PS script finished with exit code #{output.exitcode} - Output: <#{value.to_s.strip}>")
    else
      @logger.log(level: 'error', message: "PS script failed with exit code #{output.exitcode} and error message #{err}. STDOUT: #{value.to_s.strip}")
    end
  end
  value.to_s.strip
end