Class: CMD
- Inherits:
-
Hash
- Object
- Hash
- CMD
- Defined in:
- lib/cmd.rb,
lib/cmd_windows.rb
Class Method Summary collapse
Instance Method Summary collapse
- #execute ⇒ Object
- #execute_as(username) ⇒ Object
-
#initialize(cmd, options = nil) ⇒ CMD
constructor
A new instance of CMD.
- #system ⇒ Object
Constructor Details
#initialize(cmd, options = nil) ⇒ CMD
Returns a new instance of CMD.
9 10 11 12 13 14 15 16 17 |
# File 'lib/cmd.rb', line 9 def initialize(cmd, =nil) initialize_defaults if(.nil?) self[:output] = '' self[:error] = '' .each { |key, value| self[key] = value} .each { |key, value| self[key] = value} unless(.nil?) self[:command]=cmd end |
Class Method Details
.default_options(hash) ⇒ Object
20 21 22 |
# File 'lib/cmd.rb', line 20 def self.(hash) hash.each { |key, value| [key] = value} end |
Instance Method Details
#execute ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/cmd.rb', line 24 def execute puts self[:command] if(self[:echo_command] || self[:debug]) system if(self[:debug]) puts "command: #{self[:command]}" if(self[:quiet]) puts "output: #{self[:output]}" puts "error: #{self[:error]}" puts "exit_code: #{self[:exit_code]}" end if((self[:exit_code] != 0) && !self[:ignore_exit_code]) exception_text = "Exit code: #{self[:exit_code]}" exception_text = "#{exception_text}\nError: '#{self[:error]}'" exception_text = "#{exception_text}\nOutput: '#{self[:output]}'" raise Exception.new(exception_text) end end |
#execute_as(username) ⇒ Object
6 7 8 9 |
# File 'lib/cmd_windows.rb', line 6 def execute_as(username) self[:command] = "runas /noprofile /savecred /user:#{username} \"#{self[:command]}\"" wait_on_spawned_process(self) { self.execute } end |
#system ⇒ Object
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 |
# File 'lib/cmd.rb', line 43 def system begin output = {output: [], error: [] } Open3.popen3(self[:command]) do |stdin, stdout, stderr, wait_thr| self[:pid] = wait_thr.pid {:output => stdout,:error => stderr}.each do |key, stream| Thread.new do while wait_thr.alive? do if(!(char = stream.getc).nil?) output[key] << char putc char if(self[:echo_output]) else sleep(0.1) end end end end wait_thr.join self[:output] = output[:output].join unless(output[:output].empty?) self[:error] = output[:error].join unless(output[:error].empty?) self[:exit_code] = wait_thr.value.to_i end rescue Exception => e self[:error] = "#{self[:error]}\nException: #{e.to_s}" self[:exit_code]=1 unless(self[:exit_code].nil? || (self[:exit_code] == 0)) end end |