Windows Remote Management (WinRM) for Ruby
This is a SOAP library that uses the functionality in Windows Remote Management(WinRM) to call native object in Windows. This includes, but is not limited to, running batch scripts, powershell scripts and fetching WMI variables. For more information on WinRM, please visit Microsoft's WinRM site.
As of version 2.0, this gem retains the WinRM name but all powershell calls use the more modern Powershell Remoting Protocol (PSRP) for initializing runspace pools as well as creating and processing powershell pipelines.
Supported WinRM Versions
WinRM 1.1 is supported, however 2.0 and higher is recommended. See MSDN for information about WinRM versions and supported operating systems.
Install
gem install -r winrm
then on the server Enable-PSRemoting -Force
(already enabled on server operating systems 2012 and above) as admin
Example
require 'winrm'
opts = {
endpoint: 'http://myhost:5985/wsman',
user: 'administrator',
password: 'Pass@word1'
}
conn = WinRM::Connection.new(opts)
conn.shell(:powershell) do |shell|
shell.run('$PSVersionTable') do |stdout, stderr|
STDOUT.print stdout
STDERR.print stderr
end
end
Connection Options
There are various connection options you can specify upon initializing a WinRM connection object:
:transport
- The type of underlying connection transport to use (more on this below). Defaults to:negotiate
:locale
- The locale requested for response text formatting. This is the value sent in theDataLocale
andLocale
header values and defaults toen-us
:max_envelope_size
- mazimum number of bytes expected for WinRM responses. This defaults to 153600:operation_timeout
- The maximum amount of time to wait for a response from the endpoint. This defaults to 60 seconds. Note that this will not "timeout" commands that exceed this amount of time to process, it just requires the endpoint to report the status of the command before the given amount of time passes.:receive_timeout
- The amount of time given to the underlying HTTP connection to respond before timing out. The defaults to 10 seconds longer than the:operation_timeout
.:retry_limit
- the maximum number of times to retry opening a shell after failure. This defaults to 3.:retry_delay
- the amount of time to wait between retries and defaults to 10 seconds:user
- username used to authenticate over the:transport
:password
- password used to authenticate over the:transport
There are other options that may apply depending on the type of :transport
used and are discussed below.
Transports
The transport used governs the authentication method used and the encryption level used for the underlying HTTP communication with the endpoint. The WinRM gem supports the following transport types:
:negotiate
WinRM::Connection.new(
endpoint: 'http://myhost:5985/wsman',
transport: :negotiate,
user: 'administrator',
password: 'Pass@word1'
)
The :negotiate
transport uses the rubyntlm gem to authenticate with the endpoint using the NTLM protocol. This uses an HTTP based connection but the SOAP message payloads are encrypted. If using HTTP (as opposed to HTTPS) this is the recommended transport. This is also the default transport used if none is specified in the connection options.
:ssl
WinRM::Connection.new(
endpoint: 'https://myhost:59856/wsman',
transport: :ssl,
user: 'administrator',
password: 'Pass@word1'
)
The :ssl
transport establishes a connection to the winrm endpoint over a secure sockets layer transport encrypting the entire message. Here are some additional connecion options available to :ssl
connections:
:client_cert
- Either a string path to a certificate.pem
file or aX509::Certificate
object. This along with an accompanying:client_key
can be used in lieu of a:user
and:password
.:client_key
- the path to the private key file accompanying the above mentioned:client_cert
or anPKey::Pkey
object.:key_pass
- the optional password if necessary to access the:client_cert
:no_ssl_peer_verification
- when set totrue
ssl certificate validation is not performed. With a self signed cert, its a match made in heaven!:ssl_peer_fingerprint
- when this is provided, normal certificate validation is skipped and instead the given fingerprint is matched against the certificate of the endpoint for verification.:ca_trust_path
- the path to a certificate.pem
file to trust. Its similar to the:ssl_peer_fingerprint
but contains the entire certificate to trust.
:kerberos
WinRM::Connection.new(
endpoint: 'http://myhost:5985/wsman',
transport: :kerberos,
realm: 'kerberos_realm'
)
Uses :kerberos
to authenticate with the endpoint. These additional connection options may be used:
:service
- kerberos service used to authenticate with the endpoint. Defaults toHTTP
.:realm
- Kerberos realm to authenticate against.
:plaintext
Note: It is strongly recommended that you use :negotiate
instead of :plaintext
. As the name infers, the :plaintext
transport includes authentication credentials in plain text.
WinRM::Connection.new(
endpoint: 'http://myhost:5985/wsman',
transport: :plaintext,
user: 'administrator',
password: 'Pass@word1',
basic_auth_only: true
)
Additional supported connection options:
:basic_auth_only
- Force basic authentication:disable_sspi
- Disable SSPI Negotiation authentication
Shells
As of the WinRM gem version 2, one creates a shell for executing commands by calling the shell
method of a WinRM connection. There are two types of shells available:
:cmd
- initiates a traditional cmd.exe shell via the WinRM protocol:powershell
- initiates a powershell runspace via the PSRP protocol
Both shells support the same public methods: :open
, :close
, and run
. Note that when given a shell, it is opened automatically upon executing the first command via :run
. Further, close
is called automatically when a shell
is garbage collected or when using a shell from a block. However, it is always a good idea to proactively close
a shell.
Executing a WQL Query
opts = {
endpoint: 'http://myhost:5985/wsman',
user: 'administrator',
password: 'Pass@word1'
}
conn = WinRM::Connection.new(opts)
out = conn.run_wql('select * from Win32_OperatingSystem')
= out[:win32_operating_system][0][:caption]
Create a self signed cert for WinRM
You may want to create a self signed certificate for servicing https WinRM connections. You can use the following PowerShell script to create a cert and enable the WinRM HTTPS listener. Unless you are running windows server 2012 R2 or later, you must install makecert.exe from the Windows SDK, otherwise use New-SelfSignedCertificate
.
$hostname = $Env:ComputerName
C:\"Program Files"\"Microsoft SDKs"\Windows\v7.1\Bin\makecert.exe -r -pe -n "CN=$hostname,O=vagrant" -eku 1.3.6.1.5.5.7.3.1 -ss my -sr localMachine -sky exchange -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12 "$hostname.cer"
$thumbprint = (& ls cert:LocalMachine/my).Thumbprint
# Windows 2012R2 and above can use New-SelfSignedCertificate
$thumbprint = (New-SelfSignedCertificate -DnsName $hostname -CertStoreLocation cert:\LocalMachine\my).Thumbprint
$cmd = "winrm create winrm/config/Listener?Address=*+Transport=HTTPS '@{Hostname=`"$hostname`";CertificateThumbprint=`"$thumbprint`"}'"
iex $cmd
Setting up Certificate based authentication
Perform the following steps to authenticate with a certificate instead of a username and password:
Generate a certificate with an Extended Key Usage of Client Authentication and a Subject Alternative Name with the UPN of the user. See this powershell function as an example of using
openssl
to create a self signed user certificate in.pem
and.pfx
formats along with the private key file.Import the pfx file into the
TrustedPeople
directory of theLocalMachine
certificate store on the windows endpoint.Import the issuing certificate authority certificate in the endpoint's
Root
certificates. If your client certificate is self signed, this will be the client certificate.Enable certificate authentication on the endpoint:
Set-Item -Path WSMan:\localhost\Service\Auth\Certificate -Value $true
Add a winrm user mapping for the issuing certificate:
New-Item -Path WSMan:\localhost\ClientCertificate -Subject <user UPN> -URI * -Issuer <issuing certificate thumbprint> -Credential (Get-Credential) -Force
See this post for more details on certificate authentication.
Logging
The WinRM::Connection
exposes a logger
attribute and uses the logging gem to manage logging behavior. By default this appends to STDOUT
and has a level of :warn
, but one can adjust the level or add additional appenders.
conn = WinRM::Connection.new(opts)
# suppress warnings
conn.logger.level = :error
# Log to a file
conn.logger.add_appenders(Logging.appenders.file('error.log'))
If a consuming application uses its own logger that complies to the logging API, you can simply swap it in:
conn.logger = my_logger
Troubleshooting
You may have some errors like WinRM::WinRMAuthorizationError
. See this post for tips and troubleshooting steps related to winrm connection and authentication issues.
Contributing
- Fork it.
- Create a branch (git checkout -b my_feature_branch)
- Run the unit and integration tests (bundle exec rake integration)
- Commit your changes (git commit -am "Added a sweet feature")
- Push to the branch (git push origin my_feature_branch)
- Create a pull requst from your branch into master (Please be sure to provide enough detail for us to cipher what this change is doing)
Running the tests
We use Bundler to manage dependencies during development.
$ bundle install
Once you have the dependencies, you can run the unit tests with rake
:
$ bundle exec rake spec
To run the integration tests you will need a Windows box with the WinRM service properly configured. Its easiest to use a Vagrant Windows box (mwrock/Windows2012R2 is public on atlas with an evaluation version of Windows 2012 R2). You can also use mwrock/WindowsNano
provided in this repo's Vagrantfile
.
- Create a Windows VM with WinRM configured (see above).
- Copy the config-example.yml to config.yml - edit this file with your WinRM connection details.
- Run
bundle exec rake integration
WinRM Author
- Twitter: @zentourist
- BLOG: http://distributed-frostbite.blogspot.com/
- Add me in LinkedIn: http://www.linkedin.com/in/danwanek
- Find me on irc.freenode.net in #ruby-lang (zenChild)
Maintainers
- Paul Morton (https://github.com/pmorton)
- Shawn Neal (https://github.com/sneal)
- Matt Wrock (https://github.com/mwrock)