Class: WinRM::WinRMWebService
- Inherits:
-
Object
- Object
- WinRM::WinRMWebService
- Defined in:
- lib/winrm/winrm_service.rb
Overview
This is the main class that does the SOAP request/response logic. There are a few helper classes, but pretty much everything comes through here first.
Constant Summary collapse
- DEFAULT_TIMEOUT =
60
- DEFAULT_MAX_ENV_SIZE =
153600
- DEFAULT_LOCALE =
'en-US'
Instance Attribute Summary collapse
-
#endpoint ⇒ Object
readonly
Returns the value of attribute endpoint.
-
#logger ⇒ Object
Returns the value of attribute logger.
-
#output_decoder ⇒ Object
readonly
Returns the value of attribute output_decoder.
-
#retry_delay ⇒ Object
readonly
Returns the value of attribute retry_delay.
-
#retry_limit ⇒ Object
readonly
Returns the value of attribute retry_limit.
-
#timeout ⇒ Object
readonly
Returns the value of attribute timeout.
Instance Method Summary collapse
-
#cleanup_command(shell_id, command_id) ⇒ true
Clean-up after a command.
-
#close_shell(shell_id) ⇒ true
Close the shell.
-
#create_executor {|a| ... } ⇒ CommandExecutor
Creates a CommandExecutor initialized with this WinRMWebService If called with a block, create_executor yields an executor and ensures that the executor is closed after the block completes.
-
#get_command_output(shell_id, command_id, &block) ⇒ Hash
Get the Output of the given shell and command.
- #init_kerberos_transport(opts) ⇒ Object
- #init_negotiate_transport(opts) ⇒ Object
- #init_plaintext_transport(opts) ⇒ Object
- #init_ssl_transport(opts) ⇒ Object
-
#initialize(endpoint, transport = :kerberos, opts = {}) ⇒ WinRMWebService
constructor
A new instance of WinRMWebService.
-
#locale(locale) ⇒ Object
Set the locale.
-
#max_env_size(byte_sz) ⇒ Object
Max envelope size.
-
#open_shell(shell_opts = {}, &block) ⇒ String
Create a Shell on the destination host.
-
#run_cmd(command, arguments = [], &block) ⇒ Hash
(also: #cmd)
DEPRECATED: Use WinRM::CommandExecutor#run_cmd instead Run a CMD command.
-
#run_command(shell_id, command, arguments = [], cmd_opts = {}, &block) ⇒ String
Run a command on a machine with an open shell.
-
#run_powershell_script(script_file, &block) ⇒ Hash
(also: #powershell)
DEPRECATED: Use WinRM::CommandExecutor#run_powershell_script instead Run a Powershell script that resides on the local box.
-
#run_wql(wql) ⇒ Hash
(also: #wql)
Run a WQL Query.
-
#set_timeout(op_timeout_sec, receive_timeout_sec = nil) ⇒ String
(also: #op_timeout)
Operation timeout.
- #toggle_nori_type_casting(to) ⇒ Object
- #write_stdin(shell_id, command_id, stdin) ⇒ Object
Constructor Details
#initialize(endpoint, transport = :kerberos, opts = {}) ⇒ WinRMWebService
Returns a new instance of WinRMWebService.
43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/winrm/winrm_service.rb', line 43 def initialize(endpoint, transport = :kerberos, opts = {}) @endpoint = endpoint @max_env_sz = DEFAULT_MAX_ENV_SIZE @locale = DEFAULT_LOCALE @output_decoder = CommandOutputDecoder.new setup_logger configure_retries(opts) begin @xfer = send "init_#{transport}_transport", opts.merge({endpoint: endpoint}) set_timeout(DEFAULT_TIMEOUT) rescue NoMethodError raise "Invalid transport '#{transport}' specified, expected: negotiate, kerberos, plaintext, ssl." end end |
Instance Attribute Details
#endpoint ⇒ Object (readonly)
Returns the value of attribute endpoint.
32 33 34 |
# File 'lib/winrm/winrm_service.rb', line 32 def endpoint @endpoint end |
#logger ⇒ Object
Returns the value of attribute logger.
34 35 36 |
# File 'lib/winrm/winrm_service.rb', line 34 def logger @logger end |
#output_decoder ⇒ Object (readonly)
Returns the value of attribute output_decoder.
32 33 34 |
# File 'lib/winrm/winrm_service.rb', line 32 def output_decoder @output_decoder end |
#retry_delay ⇒ Object (readonly)
Returns the value of attribute retry_delay.
32 33 34 |
# File 'lib/winrm/winrm_service.rb', line 32 def retry_delay @retry_delay end |
#retry_limit ⇒ Object (readonly)
Returns the value of attribute retry_limit.
32 33 34 |
# File 'lib/winrm/winrm_service.rb', line 32 def retry_limit @retry_limit end |
#timeout ⇒ Object (readonly)
Returns the value of attribute timeout.
32 33 34 |
# File 'lib/winrm/winrm_service.rb', line 32 def timeout @timeout end |
Instance Method Details
#cleanup_command(shell_id, command_id) ⇒ true
Clean-up after a command.
291 292 293 294 295 296 297 298 299 300 301 302 303 304 |
# File 'lib/winrm/winrm_service.rb', line 291 def cleanup_command(shell_id, command_id) # Signal the Command references to terminate (close stdout/stderr) body = { "#{NS_WIN_SHELL}:Code" => 'http://schemas.microsoft.com/wbem/wsman/1/windows/shell/signal/terminate' } builder = Builder::XmlMarkup.new builder.instruct!(:xml, :encoding => 'UTF-8') builder.tag! :env, :Envelope, namespaces do |env| env.tag!(:env, :Header) { |h| h << Gyoku.xml(merge_headers(header,resource_uri_cmd,action_signal,selector_shell_id(shell_id))) } env.tag!(:env, :Body) do |env_body| env_body.tag!("#{NS_WIN_SHELL}:Signal", {'CommandId' => command_id}) { |cl| cl << Gyoku.xml(body) } end end (builder.target!) true end |
#close_shell(shell_id) ⇒ true
Close the shell
309 310 311 312 313 314 315 316 317 318 319 320 321 322 |
# File 'lib/winrm/winrm_service.rb', line 309 def close_shell(shell_id) logger.debug("[WinRM] closing remote shell #{shell_id} on #{@endpoint}") builder = Builder::XmlMarkup.new builder.instruct!(:xml, :encoding => 'UTF-8') builder.tag!('env:Envelope', namespaces) do |env| env.tag!('env:Header') { |h| h << Gyoku.xml(merge_headers(header,resource_uri_cmd,action_delete,selector_shell_id(shell_id))) } env.tag!('env:Body') end (builder.target!) logger.debug("[WinRM] remote shell #{shell_id} closed") true end |
#create_executor {|a| ... } ⇒ CommandExecutor
Creates a CommandExecutor initialized with this WinRMWebService If called with a block, create_executor yields an executor and ensures that the executor is closed after the block completes. The CommandExecutor is simply returned if no block is given.
357 358 359 360 361 362 363 364 365 366 367 368 369 370 |
# File 'lib/winrm/winrm_service.rb', line 357 def create_executor(&block) executor = CommandExecutor.new(self) executor.open if block_given? begin yield executor ensure executor.close end else executor end end |
#get_command_output(shell_id, command_id, &block) ⇒ Hash
Get the Output of the given shell and command
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 |
# File 'lib/winrm/winrm_service.rb', line 240 def get_command_output(shell_id, command_id, &block) body = { "#{NS_WIN_SHELL}:DesiredStream" => 'stdout stderr', :attributes! => {"#{NS_WIN_SHELL}:DesiredStream" => {'CommandId' => command_id}}} builder = Builder::XmlMarkup.new builder.instruct!(:xml, :encoding => 'UTF-8') builder.tag! :env, :Envelope, namespaces do |env| env.tag!(:env, :Header) { |h| h << Gyoku.xml(merge_headers(header,resource_uri_cmd,action_receive,selector_shell_id(shell_id))) } env.tag!(:env, :Body) do |env_body| env_body.tag!("#{NS_WIN_SHELL}:Receive") { |cl| cl << Gyoku.xml(body) } end end resp_doc = nil request_msg = builder.target! done_elems = [] output = Output.new while done_elems.empty? resp_doc = (request_msg) REXML::XPath.match(resp_doc, "//#{NS_WIN_SHELL}:Stream").each do |n| next if n.text.nil? || n.text.empty? decoded_text = output_decoder.decode(n.text) stream = { n.attributes['Name'].to_sym => decoded_text } output[:data] << stream yield stream[:stdout], stream[:stderr] if block_given? end # We may need to get additional output if the stream has not finished. # The CommandState will change from Running to Done like so: # @example # from... # <rsp:CommandState CommandId="..." State="http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Running"/> # to... # <rsp:CommandState CommandId="..." State="http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Done"> # <rsp:ExitCode>0</rsp:ExitCode> # </rsp:CommandState> done_elems = REXML::XPath.match(resp_doc, "//*[@State='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Done']") end output[:exitcode] = REXML::XPath.first(resp_doc, "//#{NS_WIN_SHELL}:ExitCode").text.to_i output end |
#init_kerberos_transport(opts) ⇒ Object
62 63 64 65 66 |
# File 'lib/winrm/winrm_service.rb', line 62 def init_kerberos_transport(opts) require 'gssapi' require 'gssapi/extensions' HTTP::HttpGSSAPI.new(opts[:endpoint], opts[:realm], opts[:service], opts[:keytab], opts) end |
#init_negotiate_transport(opts) ⇒ Object
58 59 60 |
# File 'lib/winrm/winrm_service.rb', line 58 def init_negotiate_transport(opts) HTTP::HttpNegotiate.new(opts[:endpoint], opts[:user], opts[:pass], opts) end |
#init_plaintext_transport(opts) ⇒ Object
68 69 70 |
# File 'lib/winrm/winrm_service.rb', line 68 def init_plaintext_transport(opts) HTTP::HttpPlaintext.new(opts[:endpoint], opts[:user], opts[:pass], opts) end |
#init_ssl_transport(opts) ⇒ Object
72 73 74 75 76 77 78 79 80 81 |
# File 'lib/winrm/winrm_service.rb', line 72 def init_ssl_transport(opts) if opts[:basic_auth_only] HTTP::BasicAuthSSL.new(opts[:endpoint], opts[:user], opts[:pass], opts) elsif opts[:client_cert] HTTP::ClientCertAuthSSL.new(opts[:endpoint], opts[:client_cert], opts[:client_key], opts[:key_pass], opts) else HTTP::HttpNegotiate.new(opts[:endpoint], opts[:user], opts[:pass], opts) end end |
#locale(locale) ⇒ Object
Set the locale
110 111 112 |
# File 'lib/winrm/winrm_service.rb', line 110 def locale(locale) @locale = locale end |
#max_env_size(byte_sz) ⇒ Object
Max envelope size
103 104 105 |
# File 'lib/winrm/winrm_service.rb', line 103 def max_env_size(byte_sz) @max_env_sz = byte_sz end |
#open_shell(shell_opts = {}, &block) ⇒ String
Create a Shell on the destination host
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 |
# File 'lib/winrm/winrm_service.rb', line 122 def open_shell(shell_opts = {}, &block) logger.debug("[WinRM] opening remote shell on #{@endpoint}") i_stream = shell_opts.has_key?(:i_stream) ? shell_opts[:i_stream] : 'stdin' o_stream = shell_opts.has_key?(:o_stream) ? shell_opts[:o_stream] : 'stdout stderr' codepage = shell_opts.has_key?(:codepage) ? shell_opts[:codepage] : 65001 # utf8 as default codepage (from https://msdn.microsoft.com/en-us/library/dd317756(VS.85).aspx) noprofile = shell_opts.has_key?(:noprofile) ? shell_opts[:noprofile] : 'FALSE' h_opts = { "#{NS_WSMAN_DMTF}:OptionSet" => { "#{NS_WSMAN_DMTF}:Option" => [noprofile, codepage], :attributes! => {"#{NS_WSMAN_DMTF}:Option" => {'Name' => ['WINRS_NOPROFILE','WINRS_CODEPAGE']}}}} shell_body = { "#{NS_WIN_SHELL}:InputStreams" => i_stream, "#{NS_WIN_SHELL}:OutputStreams" => o_stream } shell_body["#{NS_WIN_SHELL}:WorkingDirectory"] = shell_opts[:working_directory] if shell_opts.has_key?(:working_directory) shell_body["#{NS_WIN_SHELL}:IdleTimeOut"] = shell_opts[:idle_timeout] if(shell_opts.has_key?(:idle_timeout) && shell_opts[:idle_timeout].is_a?(String)) if(shell_opts.has_key?(:env_vars) && shell_opts[:env_vars].is_a?(Hash)) keys = shell_opts[:env_vars].keys vals = shell_opts[:env_vars].values shell_body["#{NS_WIN_SHELL}:Environment"] = { "#{NS_WIN_SHELL}:Variable" => vals, :attributes! => {"#{NS_WIN_SHELL}:Variable" => {'Name' => keys}} } end builder = Builder::XmlMarkup.new builder.instruct!(:xml, :encoding => 'UTF-8') builder.tag! :env, :Envelope, namespaces do |env| env.tag!(:env, :Header) { |h| h << Gyoku.xml(merge_headers(header,resource_uri_cmd,action_create,h_opts)) } env.tag! :env, :Body do |body| body.tag!("#{NS_WIN_SHELL}:Shell") { |s| s << Gyoku.xml(shell_body)} end end resp_doc = (builder.target!) shell_id = REXML::XPath.first(resp_doc, "//*[@Name='ShellId']").text logger.debug("[WinRM] remote shell #{shell_id} is open on #{@endpoint}") if block_given? begin yield shell_id ensure close_shell(shell_id) end else shell_id end end |
#run_cmd(command, arguments = [], &block) ⇒ Hash Also known as: cmd
DEPRECATED: Use WinRM::CommandExecutor#run_cmd instead Run a CMD command
330 331 332 333 334 335 |
# File 'lib/winrm/winrm_service.rb', line 330 def run_cmd(command, arguments = [], &block) logger.warn("WinRM::WinRMWebService#run_cmd is deprecated. Use WinRM::CommandExecutor#run_cmd instead") create_executor do |executor| executor.run_cmd(command, arguments, &block) end end |
#run_command(shell_id, command, arguments = [], cmd_opts = {}, &block) ⇒ String
Run a command on a machine with an open shell
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 |
# File 'lib/winrm/winrm_service.rb', line 173 def run_command(shell_id, command, arguments = [], cmd_opts = {}, &block) consolemode = cmd_opts.has_key?(:console_mode_stdin) ? cmd_opts[:console_mode_stdin] : 'TRUE' skipcmd = cmd_opts.has_key?(:skip_cmd_shell) ? cmd_opts[:skip_cmd_shell] : 'FALSE' h_opts = { "#{NS_WSMAN_DMTF}:OptionSet" => { "#{NS_WSMAN_DMTF}:Option" => [consolemode, skipcmd], :attributes! => {"#{NS_WSMAN_DMTF}:Option" => {'Name' => ['WINRS_CONSOLEMODE_STDIN','WINRS_SKIP_CMD_SHELL']}}} } body = { "#{NS_WIN_SHELL}:Command" => "\"#{command}\"", "#{NS_WIN_SHELL}:Arguments" => arguments} builder = Builder::XmlMarkup.new builder.instruct!(:xml, :encoding => 'UTF-8') builder.tag! :env, :Envelope, namespaces do |env| env.tag!(:env, :Header) { |h| h << Gyoku.xml(merge_headers(header,resource_uri_cmd,action_command,h_opts,selector_shell_id(shell_id))) } env.tag!(:env, :Body) do |env_body| env_body.tag!("#{NS_WIN_SHELL}:CommandLine") { |cl| cl << Gyoku.xml(body) } end end # Grab the command element and unescape any single quotes - issue 69 xml = builder.target! escaped_cmd = /<#{NS_WIN_SHELL}:Command>(.+)<\/#{NS_WIN_SHELL}:Command>/m.match(xml)[1] xml[escaped_cmd] = escaped_cmd.gsub(/'/, "'") resp_doc = (xml) command_id = REXML::XPath.first(resp_doc, "//#{NS_WIN_SHELL}:CommandId").text if block_given? begin yield command_id ensure cleanup_command(shell_id, command_id) end else command_id end end |
#run_powershell_script(script_file, &block) ⇒ Hash Also known as: powershell
DEPRECATED: Use WinRM::CommandExecutor#run_powershell_script instead Run a Powershell script that resides on the local box.
343 344 345 346 347 348 |
# File 'lib/winrm/winrm_service.rb', line 343 def run_powershell_script(script_file, &block) logger.warn("WinRM::WinRMWebService#run_powershell_script is deprecated. Use WinRM::CommandExecutor#run_powershell_script instead") create_executor do |executor| executor.run_powershell_script(script_file, &block) end end |
#run_wql(wql) ⇒ Hash Also known as: wql
Run a WQL Query
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 |
# File 'lib/winrm/winrm_service.rb', line 376 def run_wql(wql) body = { "#{NS_WSMAN_DMTF}:OptimizeEnumeration" => nil, "#{NS_WSMAN_DMTF}:MaxElements" => '32000', "#{NS_WSMAN_DMTF}:Filter" => wql, :attributes! => { "#{NS_WSMAN_DMTF}:Filter" => {'Dialect' => 'http://schemas.microsoft.com/wbem/wsman/1/WQL'}} } builder = Builder::XmlMarkup.new builder.instruct!(:xml, :encoding => 'UTF-8') builder.tag! :env, :Envelope, namespaces do |env| env.tag!(:env, :Header) { |h| h << Gyoku.xml(merge_headers(header,resource_uri_wmi,action_enumerate)) } env.tag!(:env, :Body) do |env_body| env_body.tag!("#{NS_ENUM}:Enumerate") { |en| en << Gyoku.xml(body) } end end resp = (builder.target!) parser = Nori.new(:parser => :rexml, :advanced_typecasting => false, :convert_tags_to => lambda { |tag| tag.snakecase.to_sym }, :strip_namespaces => true) hresp = parser.parse(resp.to_s)[:envelope][:body] # Normalize items so the type always has an array even if it's just a single item. items = {} if hresp[:enumerate_response][:items] hresp[:enumerate_response][:items].each_pair do |k,v| if v.is_a?(Array) items[k] = v else items[k] = [v] end end end items end |
#set_timeout(op_timeout_sec, receive_timeout_sec = nil) ⇒ String Also known as: op_timeout
Operation timeout.
Unless specified the client receive timeout will be 10s + the operation timeout.
93 94 95 96 97 |
# File 'lib/winrm/winrm_service.rb', line 93 def set_timeout(op_timeout_sec, receive_timeout_sec=nil) @timeout = Iso8601Duration.sec_to_dur(op_timeout_sec) @xfer.receive_timeout = receive_timeout_sec || op_timeout_sec + 10 @timeout end |
#toggle_nori_type_casting(to) ⇒ Object
412 413 414 415 |
# File 'lib/winrm/winrm_service.rb', line 412 def toggle_nori_type_casting(to) logger.warn('toggle_nori_type_casting is deprecated and has no effect, ' + 'please remove calls to it') end |
#write_stdin(shell_id, command_id, stdin) ⇒ Object
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 |
# File 'lib/winrm/winrm_service.rb', line 211 def write_stdin(shell_id, command_id, stdin) # Signal the Command references to terminate (close stdout/stderr) body = { "#{NS_WIN_SHELL}:Send" => { "#{NS_WIN_SHELL}:Stream" => { "@Name" => 'stdin', "@CommandId" => command_id, :content! => Base64.encode64(stdin) } } } builder = Builder::XmlMarkup.new builder.instruct!(:xml, :encoding => 'UTF-8') builder.tag! :env, :Envelope, namespaces do |env| env.tag!(:env, :Header) { |h| h << Gyoku.xml(merge_headers(header,resource_uri_cmd,action_send,selector_shell_id(shell_id))) } env.tag!(:env, :Body) do |env_body| env_body << Gyoku.xml(body) end end (builder.target!) true end |