Class: Bolt::Transport::WinRM::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/bolt/transport/winrm/connection.rb

Constant Summary collapse

DEFAULT_EXTENSIONS =
['.ps1', '.rb', '.pp'].freeze
HTTP_PORT =
5985
HTTPS_PORT =
5986

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(target, transport_logger) ⇒ Connection

Returns a new instance of Connection.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/bolt/transport/winrm/connection.rb', line 15

def initialize(target, transport_logger)
  @target = target

  default_port = target.options['ssl'] ? HTTPS_PORT : HTTP_PORT
  @port = @target.port || default_port
  @user = @target.user
  # Build set of extensions from extensions config as well as interpreters
  extensions = [target.options['extensions'] || []].flatten.map { |ext| ext[0] != '.' ? '.' + ext : ext }
  extensions += target.options['interpreters'].keys if target.options['interpreters']
  @extensions = DEFAULT_EXTENSIONS.to_set.merge(extensions)

  @logger = Logging.logger[@target.host]
  @transport_logger = transport_logger
end

Instance Attribute Details

#loggerObject (readonly)

Returns the value of attribute logger.



11
12
13
# File 'lib/bolt/transport/winrm/connection.rb', line 11

def logger
  @logger
end

#targetObject (readonly)

Returns the value of attribute target.



11
12
13
# File 'lib/bolt/transport/winrm/connection.rb', line 11

def target
  @target
end

Instance Method Details

#connectObject



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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
# File 'lib/bolt/transport/winrm/connection.rb', line 33

def connect
  if target.options['ssl']
    scheme = 'https'
    transport = :ssl
  else
    scheme = 'http'
    transport = :negotiate
  end
  endpoint = "#{scheme}://#{target.host}:#{@port}/wsman"
  options = { endpoint: endpoint,
              user: @user,
              password: target.password,
              retry_limit: 1,
              transport: transport,
              ca_trust_path: target.options['cacert'],
              no_ssl_peer_verification: !target.options['ssl-verify'] }

  Timeout.timeout(target.options['connect-timeout']) do
    @connection = ::WinRM::Connection.new(options)
    @connection.logger = @transport_logger

    @session = @connection.shell(:powershell)
    @session.run('$PSVersionTable.PSVersion')
    @logger.debug { "Opened session" }
  end
rescue Timeout::Error
  # If we're using the default port with SSL, a timeout probably means the
  # host doesn't support SSL.
  if target.options['ssl'] && @port == HTTPS_PORT
    the_problem = "\nVerify that required WinRM ports are open, " \
                  "or use --no-ssl if this host isn't configured to use SSL for WinRM."
  end
  raise Bolt::Node::ConnectError.new(
    "Timeout after #{target.options['connect-timeout']} seconds connecting to #{endpoint}#{the_problem}",
    'CONNECT_ERROR'
  )
rescue ::WinRM::WinRMAuthorizationError
  raise Bolt::Node::ConnectError.new(
    "Authentication failed for #{endpoint}",
    'AUTH_ERROR'
  )
rescue OpenSSL::SSL::SSLError => e
  # If we're using SSL with the default non-SSL port, mention that as a likely problem
  if target.options['ssl'] && @port == HTTP_PORT
    theres_your_problem = "\nAre you using SSL to connect to a non-SSL port?"
  end
  if target.options['ssl-verify'] && e.message.include?('certificate verify failed')
    theres_your_problem = "\nIs the remote host using a self-signed SSL"\
                          "certificate? Use --no-ssl-verify to disable "\
                          "remote host SSL verification."
  end
  raise Bolt::Node::ConnectError.new(
    "Failed to connect to #{endpoint}: #{e.message}#{theres_your_problem}",
    "CONNECT_ERROR"
  )
rescue StandardError => e
  raise Bolt::Node::ConnectError.new(
    "Failed to connect to #{endpoint}: #{e.message}",
    'CONNECT_ERROR'
  )
end

#disconnectObject



95
96
97
98
99
# File 'lib/bolt/transport/winrm/connection.rb', line 95

def disconnect
  @session&.close
  @client&.disconnect!
  @logger.debug { "Closed session" }
end

#execute(command) ⇒ Object



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/bolt/transport/winrm/connection.rb', line 110

def execute(command)
  result_output = Bolt::Node::Output.new

  @logger.debug { "Executing command: #{command}" }

  output = @session.run(command) do |stdout, stderr|
    result_output.stdout << stdout
    @logger.debug { "stdout: #{stdout}" }
    result_output.stderr << stderr
    @logger.debug { "stderr: #{stderr}" }
  end
  result_output.exit_code = output.exitcode
  if output.exitcode.zero?
    @logger.debug { "Command returned successfully" }
  else
    @logger.info { "Command failed with exit code #{output.exitcode}" }
  end
  result_output
rescue StandardError
  @logger.debug { "Command aborted" }
  raise
end

#execute_process(path = '', arguments = [], stdin = nil) ⇒ Object



133
134
135
# File 'lib/bolt/transport/winrm/connection.rb', line 133

def execute_process(path = '', arguments = [], stdin = nil)
  execute(Powershell.execute_process(path, arguments, stdin))
end

#make_tempdirObject



187
188
189
190
191
192
193
194
# File 'lib/bolt/transport/winrm/connection.rb', line 187

def make_tempdir
  find_parent = target.options['tmpdir'] ? "\"#{target.options['tmpdir']}\"" : '[System.IO.Path]::GetTempPath()'
  result = execute(Powershell.make_tempdir(find_parent))
  if result.exit_code != 0
    raise Bolt::Node::FileError.new("Could not make tempdir: #{result.stderr}", 'TEMPDIR_ERROR')
  end
  result.stdout.string.chomp
end

#mkdirs(dirs) ⇒ Object



137
138
139
140
141
142
143
# File 'lib/bolt/transport/winrm/connection.rb', line 137

def mkdirs(dirs)
  result = execute(Powershell.mkdirs(dirs))
  if result.exit_code != 0
    message = "Could not create directories: #{result.stderr}"
    raise Bolt::Node::FileError.new(message, 'MKDIR_ERROR')
  end
end

#shell_initObject



101
102
103
104
105
106
107
108
# File 'lib/bolt/transport/winrm/connection.rb', line 101

def shell_init
  return nil if @shell_initialized
  result = execute(Powershell.shell_init)
  if result.exit_code != 0
    raise BaseError.new("Could not initialize shell: #{result.stderr.string}", "SHELL_INIT_ERROR")
  end
  @shell_initialized = true
end

#validate_extensions(ext) ⇒ Object



203
204
205
206
207
208
# File 'lib/bolt/transport/winrm/connection.rb', line 203

def validate_extensions(ext)
  unless @extensions.include?(ext)
    raise Bolt::Node::FileError.new("File extension #{ext} is not enabled, "\
                        "to run it please add to 'winrm: extensions'", 'FILETYPE_ERROR')
  end
end

#with_remote_tempdirObject



196
197
198
199
200
201
# File 'lib/bolt/transport/winrm/connection.rb', line 196

def with_remote_tempdir
  dir = make_tempdir
  yield dir
ensure
  execute(Powershell.rmdir(dir))
end

#write_executable_from_content(dir, content, filename) ⇒ Object



218
219
220
221
222
223
# File 'lib/bolt/transport/winrm/connection.rb', line 218

def write_executable_from_content(dir, content, filename)
  validate_extensions(File.extname(filename))
  remote_path = "#{dir}\\#{filename}"
  write_remote_file(content, remote_path)
  remote_path
end

#write_remote_executable(dir, file, filename = nil) ⇒ Object



210
211
212
213
214
215
216
# File 'lib/bolt/transport/winrm/connection.rb', line 210

def write_remote_executable(dir, file, filename = nil)
  filename ||= File.basename(file)
  validate_extensions(File.extname(filename))
  remote_path = "#{dir}\\#{filename}"
  write_remote_file(file, remote_path)
  remote_path
end

#write_remote_file(source, destination) ⇒ Object



145
146
147
148
149
150
151
# File 'lib/bolt/transport/winrm/connection.rb', line 145

def write_remote_file(source, destination)
  if target.options['file-protocol'] == 'smb'
    write_remote_file_smb(source, destination)
  else
    write_remote_file_winrm(source, destination)
  end
end

#write_remote_file_smb(source, destination) ⇒ Object



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
# File 'lib/bolt/transport/winrm/connection.rb', line 160

def write_remote_file_smb(source, destination)
  win_dest = destination.tr('/', '\\')
  if (md = win_dest.match(/^([a-z]):\\(.*)/i))
    # if drive, use admin share for that drive, so path is '\\host\C$'
    path = "\\\\#{@target.host}\\#{md[1]}$"
    dest = md[2]
  elsif (md = win_dest.match(/^(\\\\[^\\]+\\[^\\]+)\\(.*)/))
    # if unc, path is '\\host\share'
    path = md[1]
    dest = md[2]
  else
    raise ArgumentError, "Unknown destination '#{destination}'"
  end

  client = 
  tree = client.tree_connect(path)
  begin
    write_remote_file_smb_recursive(tree, source, dest)
  ensure
    tree.disconnect!
  end
rescue ::RubySMB::Error::UnexpectedStatusCode => e
  raise Bolt::Node::FileError.new("SMB Error: #{e.message}", 'WRITE_ERROR')
rescue StandardError => e
  raise Bolt::Node::FileError.new(e.message, 'WRITE_ERROR')
end

#write_remote_file_winrm(source, destination) ⇒ Object



153
154
155
156
157
158
# File 'lib/bolt/transport/winrm/connection.rb', line 153

def write_remote_file_winrm(source, destination)
  fs = ::WinRM::FS::FileManager.new(@connection)
  fs.upload(source, destination)
rescue StandardError => e
  raise Bolt::Node::FileError.new(e.message, 'WRITE_ERROR')
end