Class WinRMClient.Builder
- Enclosing class:
- WinRMClient
WinRMClient instances: connection-scoped settings with sensible
defaults. Only the hostname and the credentials are mandatory.-
Method Summary
Modifier and TypeMethodDescriptionLet remote commands use the caller's credentials to reach a further host — a UNC path on a file server, a database, another server — likewinrs -allowdelegate.arraySeparator(String arraySeparator) Set the string that joins the elements of a WMI array property in a WQL row, such asIPAddressinWin32_NetworkAdapterConfiguration.authentication(AuthScheme... schemes) Set the authentication schemes, tried in the given order until one succeeds.build()Build the client.consoleCodePage(int consoleCodePage) Set the console code page of the remote command shell.credentials(String username, char[] password) Set the credentials (mandatory).http()Connect over HTTP (port 5985 unlessport(int)is set) — the default.https()Connect over HTTPS (port 5986 unlessport(int)is set).Load the user profile in the remote command shell — the opposite ofwinrs -noprofile.maxCommandsPerShell(int maxCommandsPerShell) Set how many commands the remote command shell runs before the client replaces it.Set the default WMI namespace for WQL queries.port(int port) Set the port.Retry transient connection failures.sslContext(SSLContext sslContext) Use a customSSLContextfor HTTPS — e.g. one built around a dedicated trust store.ticketCache(Path ticketCache) Set the Kerberos ticket cache path.Set the default timeout of every operation — a wall-clock deadline covering authentication, every WSMan round trip, and result collection.Trust every server certificate and skip hostname verification over HTTPS — for self-signed test hosts.
-
Method Details
-
https
Connect over HTTPS (port 5986 unlessport(int)is set). The server certificate is validated against the platform trust store and the hostname is verified, unlesstrustAllCertificates()orsslContext(SSLContext)says otherwise.- Returns:
- this builder
-
http
Connect over HTTP (port 5985 unlessport(int)is set) — the default. With NTLM (the default scheme) the SOAP messages are NTLM-encrypted on the wire, so plaintext HTTP is still protected. Other schemes change that guarantee: HTTP Basic sends both the credential and the SOAP in cleartext, so usehttps()with Basic. Kerberos requires HTTPS; it is rejected fail-closed atbuild()for ANY scheme list that contains it — including an ordered fallback such as(KERBEROS, NTLM)— rather than being silently dropped and downgraded to another scheme.- Returns:
- this builder
-
port
Set the port. Default: 5985 for HTTP, 5986 for HTTPS.- Parameters:
port- the TCP port (1-65535)- Returns:
- this builder
-
credentials
Set the credentials (mandatory).- Parameters:
username- the user name, plain (user) or domain-qualified (DOMAIN\\user)password- the password; the array is deliberately not copied, so the caller can wipe the single authoritative copy of the secret after closing the client- Returns:
- this builder
-
namespace
Set the default WMI namespace for WQL queries. Default:ROOT\CIMV2. Each query can override it withWqlRequest.namespace(String).- Parameters:
namespace- the WMI namespace- Returns:
- this builder
-
authentication
Set the authentication schemes, tried in the given order until one succeeds. Default: NTLM only. Kerberos requires HTTPS.- Parameters:
schemes- the schemes in fallback order, e.g.KERBEROS, NTLMorBASIC- Returns:
- this builder
-
ticketCache
Set the Kerberos ticket cache path. Default: none — Kerberos logs in with the password.- Parameters:
ticketCache- the ticket cache path- Returns:
- this builder
-
allowDelegation
Let remote commands use the caller's credentials to reach a further host — a UNC path on a file server, a database, another server — likewinrs -allowdelegate. Without it, the remote logon cannot authenticate onward, and such access fails with "access denied" (the second hop).Kerberos only: the caller's ticket-granting ticket is forwarded to the host, so it must be forwardable —
forwardable = truein the[libdefaults]section ofkrb5.conf, or a forwardable ticket in theticket cache; otherwise the first operation fails with a message saying so.build()rejects this option unlessAuthScheme.KERBEROSis among theschemes; in an ordered fallback, a connection that falls back to another scheme is not delegated.Unlike
winrs, the ticket is forwarded whether or not Active Directory trusts the host for delegation: only delegate to hosts you trust, since the host can act as the caller on the network until the ticket expires.- Returns:
- this builder
-
trustAllCertificates
Trust every server certificate and skip hostname verification over HTTPS — for self-signed test hosts. Insecure: do not use in production. This per-client setting replaces the globalorg.metricshub.winrm.tls.insecuresystem property.- Returns:
- this builder
-
sslContext
Use a customSSLContextfor HTTPS — e.g. one built around a dedicated trust store. Hostname verification stays on. Mutually exclusive withtrustAllCertificates().- Parameters:
sslContext- the TLS context providing the socket factory- Returns:
- this builder
-
timeout
Set the default timeout of every operation — a wall-clock deadline covering authentication, every WSMan round trip, and result collection. Default: 30 seconds. Each operation can override it.- Parameters:
timeout- the timeout (at least one millisecond)- Returns:
- this builder
-
retries
Retry transient connection failures. Default: no retry — any failure is reported immediately.The policy is deliberately narrow, to preserve at-most-once execution for non-idempotent commands: a WSMan round trip is retried only when it failed to establish and authenticate the connection — TCP connect, DNS resolution, the TLS handshake, or a transport error during the authentication handshake — because there the request provably never reached the server. A request that was actually sent (a command that may have started, a query that may be executing) is never retried; neither are credential rejections (
WinRMAuthenticationException) or WSMan faults (WinRMFaultException).The policy is connection-scoped: it applies to every operation on the client, including reconnections in the middle of one (WinRM connections are re-established transparently when the server drops an idle one). Retries stay inside each operation's wall-clock deadline — when the timeout elapses mid-pause, the operation fails with
WinRMTimeoutExceptionexactly as it would without a retry policy. For the streaming terminals (whose timeout is an inactivity timeout with no overall deadline), each connection attempt is bounded by that timeout, so a retried reconnection can extend the tolerated silence accordingly.WinRMClient client = WinRMClient.builder("server01") .credentials("ACME\\admin", password) .retries(2, Duration.ofSeconds(5)) // up to 2 retries, pausing 5 s before each .build();- Parameters:
retries- how many times a failed connection attempt is retried (0 disables retrying)delay- the pause before each retry (Duration.ZEROretries immediately)- Returns:
- this builder
- Throws:
IllegalArgumentException- whenretriesis negative, ordelayis null or negative
-
consoleCodePage
Set the console code page of the remote command shell. Default: 65001 (UTF-8), which makes command output UTF-8 whatever the remote locale — the right choice for reading output and for piping data to a program.An interactive session needs a different setting: under code page 65001 a remote
cmd.exedecodes the command lines it reads from its standard input one byte at a time, so every non-ASCII character is lost. Pin a single-byte code page (typically the remote machine's ANSI one,Win32_OperatingSystem.CodeSet) and use the matching charset for both directions, as the CLI'sshellsubcommand does.- Parameters:
consoleCodePage- the console code page (e.g. 1252), or 0 for the default- Returns:
- this builder
-
loadUserProfile
Load the user profile in the remote command shell — the opposite ofwinrs -noprofile. Default: the profile is not loaded, and unless something else already loaded it on the host (an interactive session, for example), commands run with the default profile:%USERPROFILE%isC:\Users\Default,%APPDATA%is not set, andHKEY_CURRENT_USERis not the user's own registry hive.The setting applies to every shell this client creates — for commands, file transfers and remote file operations — including a shell silently recreated after the server reaped the previous one.
winrsdocuments that loading the profile requires the user to be a local administrator on the host; when the host refuses it, the shell creation fails with aWinRMFaultExceptioncarrying the fault code and detail.- Returns:
- this builder
-
arraySeparator
Set the string that joins the elements of a WMI array property in a WQL row, such asIPAddressinWin32_NetworkAdapterConfiguration. Default:|("192.0.2.10|fe80::1").- Parameters:
arraySeparator- the separator (may be empty, notnull)- Returns:
- this builder
-
maxCommandsPerShell
Set how many commands the remote command shell runs before the client replaces it. Default: 10.The client reuses its command shell for commands, file transfers and remote file operations, but every command run in a shell holds one of the user's WSMan operations until the shell is deleted, even after it completed. The host caps them per user, across all of that user's connections (
MaxConcurrentOperationsPerUser: 15 on Windows Server 2008 R2, 1500 later), so a shell reused forever ends up having every command refused. Replacing the shell (one Delete and one Create, about 100 ms) releases them. The new shell gets the same working directory, environment and profile, but deleting the old one ends any process a previous command left running in it, asWinRMClient.close()does. Besides, on Windows Server 2008 R2, whose quota fault carries its WSManFault code, a command the quota refuses in a shell that already ran commands is retried once in a new shell; in a fresh shell, which holds nothing to release, the fault is reported. Later versions send that fault with no code, so this setting is what keeps a client under the quota there.A lower value leaves more of the quota to the user's other connections at the cost of more frequent replacements; 1 runs every command in a shell of its own, like
winrs.- Parameters:
maxCommandsPerShell- how many commands a shell runs before it is replaced (at least 1)- Returns:
- this builder
-
build
Build the client. This does not connect yet: the connection is established and authenticated by the first operation.- Returns:
- the client, to use with try-with-resources
- Throws:
WinRMClientException- when the configuration is rejected (e.g. Kerberos requested over HTTP, or delegation without Kerberos)
-