Skip to content

Instantly share code, notes, and snippets.

@RamblingCookieMonster
Last active February 23, 2016 12:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RamblingCookieMonster/a1645b534fed02b4b368 to your computer and use it in GitHub Desktop.
Save RamblingCookieMonster/a1645b534fed02b4b368 to your computer and use it in GitHub Desktop.
zSSH.ps-winrb.rb
#!/usr/local/bin/ruby
# Point this to your ruby binary as desired...
require 'winrm'
require 'optparse'
require 'io/console'
require 'logger'
# Default values
params = Hash[
:password => '*',
:username => 'REDACTED\wframe',
:uri => 'http://ts1:5985/wsman'
]
# Who knows if this is the right route for verbose output
logg = Logger.new(STDOUT)
logg.level = Logger::WARN
logg.datetime_format = "%Y-%m-%d %H:%M:%S"
# Parse ze args
# We should make -c take remaining positional arguments, but this is quick and dirty...
OptionParser.new do |opts|
opts.banner = "Usage: winrm.rb [options]"
opts.on('-a', '--uri ADDRESS', String, 'Connection URI') { |v| params[:uri] = v }
opts.on('-u', '--username USERNAME', String, 'User name') { |v| params[:username] = v }
opts.on('-p', '--password PASSWORD', String, 'Password. Prompt if not specified') { |v| params[:password] = v }
opts.on('-v', '--verbose', 'Run verbosely') { logg.level = Logger::INFO }
opts.on('-c', '--command POWERSHELLCODE', 'Run arbitrary PowerShell code. Beware string parsing \\$') { |v| params[:command] = v }
end.parse!
# No user/PW? get them
unless params.key?(:username)
print "Enter Username: "
params[:username] = STDIN.gets.chomp
end
unless params.key?(:password) && params[:password] != '*'
print "Enter Password:\n"
params[:password] = STDIN.noecho(&:gets).chomp
end
# Output the params. Maybe don't show the password. Probably a more appropiate way to do this.
logg.info {
cleaned = params.clone
cleaned.delete(:password)
cleaned
}
# WinRM fun
winrm = WinRM::WinRMWebService.new(params[:uri],
:negotiate,
:user => params[:username],
:pass => params[:password])
winrm.create_executor do |executor|
executor.run_powershell_script(params[:command]) do |stdout, stderr|
STDOUT.print stdout
STDERR.print stderr
end
end
# Side note...
# I ran into issues where I would get a "Safe handle has been closed" error, among other issues.
# Couldn't find any config issues, WinRM from the local box worked, and other common misconfigurations were not in play...
# Ultimately, got fed up, restarted, and it everything started playing nicely.
# I don't like that...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment