Skip to main content

WinrmClient

Struct WinrmClient 

Source
pub struct WinrmClient { /* private fields */ }
Expand description

Async WinRM (WS-Management) HTTP client.

Manages the full remote-shell lifecycle: create a shell, execute commands, poll output, signal termination, and delete the shell. Each high-level method (run_command, run_powershell) handles this lifecycle automatically; the lower-level methods are available for callers that need finer control.

The client is cheaply cloneable via the inner reqwest::Client connection pool but is not Clone itself – create one per logical session.

Implementations§

Source§

impl WinrmClient

Source

pub fn new( config: WinrmConfig, credentials: WinrmCredentials, ) -> Result<Self, WinrmError>

Create a new WinrmClient from the given configuration and credentials.

Builds the underlying HTTP client with the configured timeouts and TLS settings. Returns WinrmError::Http if the HTTP client cannot be constructed (e.g. invalid TLS configuration).

Source

pub fn builder(config: WinrmConfig) -> WinrmClientBuilder

Create a WinrmClientBuilder for constructing a client with the typestate builder pattern.

Source

pub async fn create_shell(&self, host: &str) -> Result<String, WinrmError>

Create a new remote shell on the given host. Returns the shell ID.

The shell uses UTF-8 codepage (65001) and disables the user profile (WINRS_NOPROFILE). The caller must eventually call delete_shell to release server resources.

Source

pub async fn open_psrp_shell( &self, host: &str, creation_xml_b64: &str, resource_uri: &str, ) -> Result<Shell<'_>, WinrmError>

Create a PSRP (PowerShell Remoting) shell on the given host.

Unlike Self::create_shell this uses the PowerShell resource URI and embeds the creationXml (base64-encoded PSRP opening fragments) directly in the Create Shell body.

Returns a Shell whose subsequent operations (Execute, Receive, Send, Signal, Delete) will use the PowerShell resource URI.

Source

pub async fn execute_command( &self, host: &str, shell_id: &str, command: &str, args: &[&str], ) -> Result<String, WinrmError>

Execute a command in an existing remote shell. Returns the command ID.

The caller is responsible for subsequently calling receive_output to poll for results.

Source

pub async fn receive_output( &self, host: &str, shell_id: &str, command_id: &str, ) -> Result<ReceiveOutput, WinrmError>

Poll for command output (stdout, stderr, exit code, and completion flag).

Must be called repeatedly until ReceiveOutput::done is true. Each call may return partial output that should be accumulated.

Source

pub async fn signal_terminate( &self, host: &str, shell_id: &str, command_id: &str, ) -> Result<(), WinrmError>

Send a terminate signal to a running command.

This is a best-effort operation – errors are typically non-fatal since the shell will be deleted shortly after.

Source

pub async fn delete_shell( &self, host: &str, shell_id: &str, ) -> Result<(), WinrmError>

Delete (close) a remote shell, releasing server-side resources.

Should always be called after command execution is complete, even if an error occurred. The high-level run_command and run_powershell methods handle this automatically.

Source

pub async fn run_command( &self, host: &str, command: &str, args: &[&str], ) -> Result<CommandOutput, WinrmError>

Run a command on a remote host, collecting all output.

This is the primary entry point for command execution. It handles the full shell lifecycle: create -> execute -> poll -> signal -> delete. The shell is always cleaned up, even if the command fails.

Source

pub async fn run_powershell( &self, host: &str, script: &str, ) -> Result<CommandOutput, WinrmError>

Run a PowerShell script on a remote host.

The script is encoded as UTF-16LE base64 and executed via powershell.exe -EncodedCommand, which avoids quoting and escaping issues. Internally delegates to run_command.

Source

pub async fn run_command_with_cancel( &self, host: &str, command: &str, args: &[&str], cancel: CancellationToken, ) -> Result<CommandOutput, WinrmError>

Execute a command with cancellation support.

Like run_command, but can be cancelled via a CancellationToken.

Source

pub async fn run_powershell_with_cancel( &self, host: &str, script: &str, cancel: CancellationToken, ) -> Result<CommandOutput, WinrmError>

Execute a PowerShell script with cancellation support.

Like run_powershell, but can be cancelled via a CancellationToken.

Source

pub async fn run_wql( &self, host: &str, query: &str, namespace: Option<&str>, ) -> Result<String, WinrmError>

Execute a WQL query against WMI via WS-Enumeration.

Returns the raw XML response items as a string. The response contains WMI object instances matching the query. Use a namespace of None for the default root/cimv2.

§Example
let xml = client.run_wql("server", "SELECT Name,State FROM Win32_Service", None).await?;
println!("{xml}");
Source

pub async fn open_shell(&self, host: &str) -> Result<Shell<'_>, WinrmError>

Open a reusable shell session on the given host.

Returns a Shell that can execute multiple commands without the overhead of creating and deleting a shell each time.

The shell should be explicitly closed via Shell::close when done. If dropped without closing, a warning is logged.

Source

pub async fn reconnect_shell( &self, host: &str, shell_id: &str, resource_uri: &str, ) -> Result<Shell<'_>, WinrmError>

Reconnect to a previously-disconnected shell.

Sends a WS-Man Reconnect SOAP request to validate that the server-side shell identified by shell_id is still alive and returns a Shell handle that resumes operations on it.

Source§

impl WinrmClient

Source

pub async fn upload_file( &self, host: &str, local_path: &Path, remote_path: &str, ) -> Result<u64, WinrmError>

Upload a local file to a remote Windows host.

The file is chunked into ~2 KB pieces, base64-encoded, and written via PowerShell [IO.File]::WriteAllBytes / [IO.File]::Open('Append'). The small chunk size is dictated by the WinRS command-line limit (~8191 chars) after triple encoding (base64 → UTF-16LE → base64).

Returns the number of bytes uploaded.

Source

pub async fn download_file( &self, host: &str, remote_path: &str, local_path: &Path, ) -> Result<u64, WinrmError>

Download a file from a remote Windows host.

Reads the file via PowerShell base64 encoding and decodes locally.

Returns the number of bytes downloaded.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more