Skip to content

Instantly share code, notes, and snippets.

@kernelsmith
Created April 17, 2013 19:44
Show Gist options
  • Save kernelsmith/5407160 to your computer and use it in GitHub Desktop.
Save kernelsmith/5407160 to your computer and use it in GitHub Desktop.
Run shell commands, powershell scripts, WQL queries etc via winrm in ruby
require 'winrm' # winrm depends on nokogiri
require 'csv'
# file path for the csv of ips etc
ip_file = "./vms.csv"
# commands to be run on each
cmds = [
"tzutil /s utc_dstoff",
"date /t",
"time /t", # don't forget the commas, this is an array
]
# commands for which you always want to see output
always_show_output_from = [
"date /t",
"time /t", # commas
]
hardcoded_user = nil # if this has any value other than nil, it will override user in csv file
hardcoded_pass = nil # if this has any value other than nil, it will override pass in csv file
# headers for the csv are expected to be hostname, ip, user, and pass but in any order
# you can specify you're own headers if they aren't in the file's first row by passing
# an array to the :headers option, like {:headers = ["hostname", "ip", "user", "pass"]}
CSV.foreach(ip_file, {:headers => :first_row}) do |row|
next unless row["ip"]
#require 'pp'
#pp row
pass = hardcoded_pass || row["pass"]
user = hardcoded_user || row["user"]
endpoint = "http://#{row["ip"]}:5985/wsman"
#puts "Using #{endpoint}, #{user}, #{pass}"
winrm = WinRM::WinRMWebService.new(endpoint, :plaintext, :user => user, :pass => pass, :basic_auth_only => true)
#pp winrm
cmds.each do |cmd|
puts "Running #{cmd} on #{row["ip"]} (#{row["hostname"]})"
if always_show_output_from.include? cmd
# this is for things you want to display the output from no matter what, like ipconfig or time /t
results = winrm.cmd(cmd) do |stdout, stderr|
STDOUT.print stdout
STDERR.print stderr
end
else
results = winrm.cmd(cmd)
end
#pp results
if not results[:exitcode] == 0 # <= this should be 0 in almost all cases
puts "*** FAILURE ***from #{row["ip"]} (#{row["hostname"]}) running #{cmd}"
puts results[:data].to_s
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment