Class: Bolt::Shell::Powershell
- Inherits:
-
Bolt::Shell
- Object
- Bolt::Shell
- Bolt::Shell::Powershell
- Defined in:
- lib/bolt/shell/powershell.rb,
lib/bolt/shell/powershell/snippets.rb
Defined Under Namespace
Modules: Snippets
Constant Summary collapse
- DEFAULT_EXTENSIONS =
Set.new(%w[.ps1 .rb .pp])
- PS_ARGS =
%w[-NoProfile -NonInteractive -NoLogo -ExecutionPolicy Bypass].freeze
Instance Attribute Summary
Attributes inherited from Bolt::Shell
Instance Method Summary collapse
- #default_input_method(executable) ⇒ Object
- #download(source, destination, _options = {}) ⇒ Object
- #env_declarations(env_vars) ⇒ Object
- #escape_arguments(arguments) ⇒ Object
- #execute(command, wrap_command = false) ⇒ Object
- #execute_process(path, arguments, stdin = nil) ⇒ Object
-
#initialize(target, conn) ⇒ Powershell
constructor
A new instance of Powershell.
- #make_tmpdir ⇒ Object
- #mkdirs(dirs) ⇒ Object
- #powershell_file?(path) ⇒ Boolean
- #process_from_extension(path) ⇒ Object
- #provided_features ⇒ Object
- #quote_string(string) ⇒ Object
- #rmdir(dir) ⇒ Object
- #run_command(command, options = {}, position = []) ⇒ Object
- #run_ps_task(task_path, arguments, input_method) ⇒ Object
- #run_script(script, arguments, options = {}, position = []) ⇒ Object
- #run_task(task, arguments, _options = {}, position = []) ⇒ Object
- #upload(source, destination, _options = {}) ⇒ Object
- #validate_extensions(ext) ⇒ Object
- #validate_ps_version ⇒ Object
- #with_tmpdir ⇒ Object
- #write_executable(dir, file, filename = nil) ⇒ Object
Methods inherited from Bolt::Shell
#envify_params, #select_implementation, #select_interpreter, #unwrap_sensitive_args
Constructor Details
#initialize(target, conn) ⇒ Powershell
Returns a new instance of Powershell.
11 12 13 14 15 16 17 18 |
# File 'lib/bolt/shell/powershell.rb', line 11 def initialize(target, conn) super extensions = [target.['extensions'] || []].flatten.map { |ext| ext[0] == '.' ? ext : '.' + ext } extensions += target.['interpreters'].keys if target.['interpreters'] @extensions = DEFAULT_EXTENSIONS + extensions validate_ps_version end |
Instance Method Details
#default_input_method(executable) ⇒ Object
39 40 41 |
# File 'lib/bolt/shell/powershell.rb', line 39 def default_input_method(executable) powershell_file?(executable) ? 'powershell' : 'both' end |
#download(source, destination, _options = {}) ⇒ Object
187 188 189 190 191 |
# File 'lib/bolt/shell/powershell.rb', line 187 def download(source, destination, = {}) download = File.join(destination, Bolt::Util.windows_basename(source)) conn.download_file(source, destination, download) Bolt::Result.for_download(target, source, destination, download) end |
#env_declarations(env_vars) ⇒ Object
90 91 92 93 94 |
# File 'lib/bolt/shell/powershell.rb', line 90 def env_declarations(env_vars) env_vars.map do |var, val| "[Environment]::SetEnvironmentVariable('#{var}', @'\n#{val}\n'@)" end end |
#escape_arguments(arguments) ⇒ Object
80 81 82 83 84 85 86 87 88 |
# File 'lib/bolt/shell/powershell.rb', line 80 def escape_arguments(arguments) arguments.map do |arg| if arg =~ / / "\"#{arg}\"" else arg end end end |
#execute(command, wrap_command = false) ⇒ Object
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 |
# File 'lib/bolt/shell/powershell.rb', line 288 def execute(command, wrap_command = false) if (conn.max_command_length && command.length > conn.max_command_length) || wrap_command return with_tmpdir do |dir| command += "\r\nif (!$?) { if($LASTEXITCODE) { exit $LASTEXITCODE } else { exit 1 } }" script_file = File.join(dir, "#{SecureRandom.uuid}_wrapper.ps1") conn.upload_file(StringIO.new(command), script_file) args = escape_arguments([script_file]) script_invocation = ['powershell.exe', *PS_ARGS, '-File', *args].join(' ') execute(script_invocation) end end inp, out, err, t = conn.execute(command) result = Bolt::Node::Output.new inp.close stdout = Thread.new do # Set to binmode to preserve \r\n line endings, but save and restore # the proper encoding so the string isn't later misinterpreted encoding = out.external_encoding out.binmode result.stdout << out.read.force_encoding(encoding) end stderr = Thread.new do encoding = err.external_encoding err.binmode result.stderr << err.read.force_encoding(encoding) end stdout.join stderr.join result.exit_code = t.value.respond_to?(:exitstatus) ? t.value.exitstatus : t.value result end |
#execute_process(path, arguments, stdin = nil) ⇒ Object
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
# File 'lib/bolt/shell/powershell.rb', line 108 def execute_process(path, arguments, stdin = nil) quoted_args = arguments.map { |arg| quote_string(arg) }.join(' ') quoted_path = if path =~ /^'.*'$/ || path =~ /^".*"$/ path else quote_string(path) end exec_cmd = if stdin.nil? "& #{quoted_path} #{quoted_args}" else <<~STR $command_stdin = @' #{stdin} '@ $command_stdin | & #{quoted_path} #{quoted_args} STR end Snippets.execute_process(exec_cmd) end |
#make_tmpdir ⇒ Object
141 142 143 144 145 146 147 148 |
# File 'lib/bolt/shell/powershell.rb', line 141 def make_tmpdir find_parent = target.['tmpdir'] ? "\"#{target.['tmpdir']}\"" : '[System.IO.Path]::GetTempPath()' result = execute(Snippets.make_tmpdir(find_parent)) if result.exit_code != 0 raise Bolt::Node::FileError.new("Could not make tmpdir: #{result.stderr.string}", 'TMPDIR_ERROR') end result.stdout.string.chomp end |
#mkdirs(dirs) ⇒ Object
131 132 133 134 135 136 137 138 139 |
# File 'lib/bolt/shell/powershell.rb', line 131 def mkdirs(dirs) paths = dirs.uniq.sort.join('","') mkdir_command = "mkdir -Force -Path (\"#{paths}\")" result = execute(mkdir_command) if result.exit_code != 0 = "Could not create directories: #{result.stderr.string}" raise Bolt::Node::FileError.new(, 'MKDIR_ERROR') end end |
#powershell_file?(path) ⇒ Boolean
43 44 45 |
# File 'lib/bolt/shell/powershell.rb', line 43 def powershell_file?(path) File.extname(path).downcase == '.ps1' end |
#process_from_extension(path) ⇒ Object
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 |
# File 'lib/bolt/shell/powershell.rb', line 54 def process_from_extension(path) case Pathname(path).extname.downcase when '.rb' [ 'ruby.exe', %W[-S "#{path}"] ] when '.ps1' [ 'powershell.exe', [*PS_ARGS, '-File', path] ] when '.pp' [ 'puppet.bat', %W[apply "#{path}"] ] else # Run the script via cmd, letting Windows extension handling determine how [ 'cmd.exe', %W[/c "#{path}"] ] end end |
#provided_features ⇒ Object
35 36 37 |
# File 'lib/bolt/shell/powershell.rb', line 35 def provided_features ['powershell'] end |
#quote_string(string) ⇒ Object
96 97 98 |
# File 'lib/bolt/shell/powershell.rb', line 96 def quote_string(string) "'" + string.gsub("'", "''") + "'" end |
#rmdir(dir) ⇒ Object
150 151 152 |
# File 'lib/bolt/shell/powershell.rb', line 150 def rmdir(dir) execute(Snippets.rmdir(dir)) end |
#run_command(command, options = {}, position = []) ⇒ Object
193 194 195 196 197 198 199 200 201 202 203 204 205 |
# File 'lib/bolt/shell/powershell.rb', line 193 def run_command(command, = {}, position = []) command = [*env_declarations([:env_vars]), command].join("\r\n") if [:env_vars] wrap_command = conn.is_a?(Bolt::Transport::Local::Connection) output = execute(command, wrap_command) Bolt::Result.for_command(target, output.stdout.string, output.stderr.string, output.exit_code, 'command', command, position) end |
#run_ps_task(task_path, arguments, input_method) ⇒ Object
171 172 173 174 175 176 177 178 179 180 |
# File 'lib/bolt/shell/powershell.rb', line 171 def run_ps_task(task_path, arguments, input_method) # NOTE: cannot redirect STDIN to a .ps1 script inside of PowerShell # must create new powershell.exe process like other interpreters # fortunately, using PS with stdin input_method should never happen if input_method == 'powershell' Snippets.ps_task(task_path, arguments) else Snippets.try_catch(task_path) end end |
#run_script(script, arguments, options = {}, position = []) ⇒ Object
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 |
# File 'lib/bolt/shell/powershell.rb', line 207 def run_script(script, arguments, = {}, position = []) # unpack any Sensitive data arguments = unwrap_sensitive_args(arguments) with_tmpdir do |dir| script_path = write_executable(dir, script) command = if powershell_file?(script_path) Snippets.run_script(arguments, script_path) else path, args = *process_from_extension(script_path) args += escape_arguments(arguments) execute_process(path, args) end command = [*env_declarations([:env_vars]), command].join("\r\n") if [:env_vars] output = execute(command) Bolt::Result.for_command(target, output.stdout.string, output.stderr.string, output.exit_code, 'script', script, position) end end |
#run_task(task, arguments, _options = {}, position = []) ⇒ Object
232 233 234 235 236 237 238 239 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 285 286 |
# File 'lib/bolt/shell/powershell.rb', line 232 def run_task(task, arguments, = {}, position = []) implementation = select_implementation(target, task) executable = implementation['path'] input_method = implementation['input_method'] extra_files = implementation['files'] input_method ||= powershell_file?(executable) ? 'powershell' : 'both' # unpack any Sensitive data arguments = unwrap_sensitive_args(arguments) with_tmpdir do |dir| if extra_files.empty? task_dir = dir else # TODO: optimize upload of directories arguments['_installdir'] = dir task_dir = File.join(dir, task.tasks_dir) mkdirs([task_dir] + extra_files.map { |file| File.join(dir, File.dirname(file['name'])) }) extra_files.each do |file| conn.upload_file(file['path'], File.join(dir, file['name'])) end end task_path = write_executable(task_dir, executable) if Bolt::Task::STDIN_METHODS.include?(input_method) stdin = JSON.dump(arguments) end command = if powershell_file?(task_path) && stdin.nil? run_ps_task(task_path, arguments, input_method) else if (interpreter = select_interpreter(task_path, target.['interpreters'])) path = interpreter args = [task_path] else path, args = *process_from_extension(task_path) end execute_process(path, args, stdin) end env_assignments = if Bolt::Task::ENVIRONMENT_METHODS.include?(input_method) env_declarations(envify_params(arguments)) else [] end output = execute([Snippets.shell_init, *env_assignments, command].join("\n")) Bolt::Result.for_task(target, output.stdout.string, output.stderr.string, output.exit_code, task.name, position) end end |
#upload(source, destination, _options = {}) ⇒ Object
182 183 184 185 |
# File 'lib/bolt/shell/powershell.rb', line 182 def upload(source, destination, = {}) conn.upload_file(source, destination) Bolt::Result.for_upload(target, source, destination) end |
#validate_extensions(ext) ⇒ Object
47 48 49 50 51 52 |
# File 'lib/bolt/shell/powershell.rb', line 47 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 |
#validate_ps_version ⇒ Object
20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/bolt/shell/powershell.rb', line 20 def validate_ps_version version = execute("$PSVersionTable.PSVersion.Major").stdout.string.chomp if !version.empty? && version.to_i < 3 # This lets us know how many targets have Powershell 2, and lets the # user know how many targets they have with PS2 msg = "Detected PowerShell 2 on one or more targets.\nPowerShell 2 "\ "is deprecated, and support will be removed in Bolt 3.0. See "\ "bolt-debug.log or run with '--log-level debug' to see the full "\ "list of targets with PowerShell 2." Bolt::Logger.deprecate_once("powershell_2", msg) @logger.debug("Detected PowerShell 2 on #{target}.") end end |
#with_tmpdir ⇒ Object
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 |
# File 'lib/bolt/shell/powershell.rb', line 154 def with_tmpdir unless @tmpdir # Only cleanup the directory afterward if we made it to begin with owner = true @tmpdir = make_tmpdir end yield @tmpdir ensure if owner && @tmpdir if target.['cleanup'] rmdir(@tmpdir) else Bolt::Logger.warn("Skipping cleanup of tmpdir '#{@tmpdir}'", "skip_cleanup") end end end |
#write_executable(dir, file, filename = nil) ⇒ Object
100 101 102 103 104 105 106 |
# File 'lib/bolt/shell/powershell.rb', line 100 def write_executable(dir, file, filename = nil) filename ||= File.basename(file) validate_extensions(File.extname(filename)) destination = "#{dir}\\#{filename}" conn.upload_file(file, destination) destination end |