Class WinRMClient.Builder

java.lang.Object
org.metricshub.winrm.WinRMClient.Builder
Enclosing class:
WinRMClient

public static final class WinRMClient.Builder extends Object
Builder of WinRMClient instances: connection-scoped settings with sensible defaults. Only the hostname and the credentials are mandatory.
  • Method Details

    • https

      public WinRMClient.Builder https()
      Connect over HTTPS (port 5986 unless port(int) is set). The server certificate is validated against the platform trust store and the hostname is verified, unless trustAllCertificates() or sslContext(SSLContext) says otherwise.
      Returns:
      this builder
    • http

      public WinRMClient.Builder http()
      Connect over HTTP (port 5985 unless port(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 use https() with Basic. Kerberos requires HTTPS; it is rejected fail-closed at build() 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

      public WinRMClient.Builder port(int port)
      Set the port. Default: 5985 for HTTP, 5986 for HTTPS.
      Parameters:
      port - the TCP port (1-65535)
      Returns:
      this builder
    • credentials

      public WinRMClient.Builder credentials(String username, char[] password)
      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

      public WinRMClient.Builder namespace(String namespace)
      Set the default WMI namespace for WQL queries. Default: ROOT\CIMV2. Each query can override it with WqlRequest.namespace(String).
      Parameters:
      namespace - the WMI namespace
      Returns:
      this builder
    • authentication

      public WinRMClient.Builder authentication(AuthScheme... schemes)
      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, NTLM or BASIC
      Returns:
      this builder
    • ticketCache

      public WinRMClient.Builder ticketCache(Path 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

      public WinRMClient.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 — like winrs -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 = true in the [libdefaults] section of krb5.conf, or a forwardable ticket in the ticket cache; otherwise the first operation fails with a message saying so. build() rejects this option unless AuthScheme.KERBEROS is among the schemes; 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

      public WinRMClient.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 global org.metricshub.winrm.tls.insecure system property.
      Returns:
      this builder
    • sslContext

      public WinRMClient.Builder sslContext(SSLContext sslContext)
      Use a custom SSLContext for HTTPS — e.g. one built around a dedicated trust store. Hostname verification stays on. Mutually exclusive with trustAllCertificates().
      Parameters:
      sslContext - the TLS context providing the socket factory
      Returns:
      this builder
    • timeout

      public WinRMClient.Builder timeout(Duration 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

      public WinRMClient.Builder retries(int retries, Duration delay)
      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 WinRMTimeoutException exactly 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.ZERO retries immediately)
      Returns:
      this builder
      Throws:
      IllegalArgumentException - when retries is negative, or delay is null or negative
    • consoleCodePage

      public WinRMClient.Builder consoleCodePage(int 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.exe decodes 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's shell subcommand does.

      Parameters:
      consoleCodePage - the console code page (e.g. 1252), or 0 for the default
      Returns:
      this builder
    • loadUserProfile

      public WinRMClient.Builder loadUserProfile()
      Load the user profile in the remote command shell — the opposite of winrs -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% is C:\Users\Default, %APPDATA% is not set, and HKEY_CURRENT_USER is 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. winrs documents 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 a WinRMFaultException carrying the fault code and detail.

      Returns:
      this builder
    • arraySeparator

      public WinRMClient.Builder arraySeparator(String arraySeparator)
      Set the string that joins the elements of a WMI array property in a WQL row, such as IPAddress in Win32_NetworkAdapterConfiguration. Default: | ("192.0.2.10|fe80::1").
      Parameters:
      arraySeparator - the separator (may be empty, not null)
      Returns:
      this builder
    • maxCommandsPerShell

      public WinRMClient.Builder maxCommandsPerShell(int 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, as WinRMClient.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

      public WinRMClient 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)