pub struct Session<T: AsyncReadExt + AsyncWriteExt + Unpin + Send> { /* private fields */ }Expand description
A session handle for interacting with a spawned process.
The session provides methods to send input, expect patterns in output, and manage the lifecycle of the process.
Implementations§
Source§impl<T: AsyncReadExt + AsyncWriteExt + Unpin + Send> Session<T>
impl<T: AsyncReadExt + AsyncWriteExt + Unpin + Send> Session<T>
Sourcepub fn new(transport: T, config: SessionConfig) -> Self
pub fn new(transport: T, config: SessionConfig) -> Self
Create a new session with the given transport.
Sourcepub const fn state(&self) -> SessionState
pub const fn state(&self) -> SessionState
Get the current session state.
Sourcepub const fn config(&self) -> &SessionConfig
pub const fn config(&self) -> &SessionConfig
Get the session configuration.
Sourcepub fn clear_buffer(&mut self)
pub fn clear_buffer(&mut self)
Clear the buffer.
Sourcepub const fn pattern_manager(&self) -> &PatternManager
pub const fn pattern_manager(&self) -> &PatternManager
Get the pattern manager for before/after patterns.
Sourcepub const fn pattern_manager_mut(&mut self) -> &mut PatternManager
pub const fn pattern_manager_mut(&mut self) -> &mut PatternManager
Get mutable access to the pattern manager.
Sourcepub const fn set_state(&mut self, state: SessionState)
pub const fn set_state(&mut self, state: SessionState)
Set the session state.
Sourcepub async fn send_line(&mut self, line: &str) -> Result<()>
pub async fn send_line(&mut self, line: &str) -> Result<()>
Send a line to the process (appends newline based on config).
§Errors
Returns an error if the write fails.
Sourcepub async fn send_control(&mut self, ctrl: ControlChar) -> Result<()>
pub async fn send_control(&mut self, ctrl: ControlChar) -> Result<()>
Sourcepub async fn expect(&mut self, pattern: impl Into<Pattern>) -> Result<Match>
pub async fn expect(&mut self, pattern: impl Into<Pattern>) -> Result<Match>
Expect a pattern in the output.
Blocks until the pattern is matched, EOF is detected, or timeout occurs.
§Errors
Returns an error on timeout, EOF (if not expected), or I/O error.
Sourcepub async fn expect_any(&mut self, patterns: &PatternSet) -> Result<Match>
pub async fn expect_any(&mut self, patterns: &PatternSet) -> Result<Match>
Expect any of the given patterns.
§Errors
Returns an error on timeout, EOF (if not expected), or I/O error.
Sourcepub async fn expect_timeout(
&mut self,
pattern: impl Into<Pattern>,
timeout: Duration,
) -> Result<Match>
pub async fn expect_timeout( &mut self, pattern: impl Into<Pattern>, timeout: Duration, ) -> Result<Match>
Sourcepub async fn wait(&mut self) -> Result<ProcessExitStatus>
pub async fn wait(&mut self) -> Result<ProcessExitStatus>
Wait for the process to exit.
This method blocks until EOF is detected on the session, which typically happens when the child process terminates.
§Warning
This method has no timeout and may block indefinitely if the process
does not exit. Consider using wait_timeout or
expect_eof_timeout for bounded waits.
§Errors
Returns an error if waiting fails due to I/O error.
Sourcepub async fn wait_timeout(
&mut self,
timeout: Duration,
) -> Result<ProcessExitStatus>
pub async fn wait_timeout( &mut self, timeout: Duration, ) -> Result<ProcessExitStatus>
Sourcepub fn check(&mut self, pattern: &Pattern) -> Option<MatchResult>
pub fn check(&mut self, pattern: &Pattern) -> Option<MatchResult>
Check if a pattern matches immediately without blocking.
Sourcepub const fn transport(&self) -> &Arc<Mutex<T>>
pub const fn transport(&self) -> &Arc<Mutex<T>>
Get the underlying transport.
Use with caution as direct access bypasses session management.
Sourcepub fn interact(&self) -> InteractBuilder<'_, T>where
T: 'static,
pub fn interact(&self) -> InteractBuilder<'_, T>where
T: 'static,
Start an interactive session with pattern hooks.
This returns a builder that allows you to configure pattern-based callbacks that fire when patterns match in the output or input.
§Example
use rust_expect::{Session, InteractAction};
#[tokio::main]
async fn main() -> Result<(), rust_expect::ExpectError> {
let mut session = Session::spawn("/bin/bash", &[]).await?;
session.interact()
.on_output("password:", |ctx| {
ctx.send("my_password\n")
})
.on_output("logout", |_| {
InteractAction::Stop
})
.start()
.await?;
Ok(())
}Sourcepub async fn run_dialog(&mut self, dialog: &Dialog) -> Result<DialogResult>
pub async fn run_dialog(&mut self, dialog: &Dialog) -> Result<DialogResult>
Run a dialog on this session.
A dialog is a predefined sequence of expect/send operations. This method executes the dialog and returns the result.
§Example
use rust_expect::{Session, Dialog, DialogStep};
#[tokio::main]
async fn main() -> Result<(), rust_expect::ExpectError> {
let mut session = Session::spawn("/bin/bash", &[]).await?;
let dialog = Dialog::named("shell_test")
.step(DialogStep::new("prompt")
.with_expect("$")
.with_send("echo hello\n"))
.step(DialogStep::new("verify")
.with_expect("hello"));
let result = session.run_dialog(&dialog).await?;
assert!(result.success);
Ok(())
}§Errors
Returns an error if I/O fails. Step-level timeouts are reported
in the DialogResult rather than as errors.
Sourcepub async fn run_dialog_with(
&mut self,
dialog: &Dialog,
executor: &DialogExecutor,
) -> Result<DialogResult>
pub async fn run_dialog_with( &mut self, dialog: &Dialog, executor: &DialogExecutor, ) -> Result<DialogResult>
Run a dialog with a custom executor.
This allows customizing the executor settings (max steps, default timeout).
§Errors
Returns an error if I/O fails.
Sourcepub async fn expect_eof(&mut self) -> Result<Match>
pub async fn expect_eof(&mut self) -> Result<Match>
Expect end-of-file (process termination).
This is a convenience method for waiting until the process terminates and closes its output stream.
§Example
use rust_expect::Session;
#[tokio::main]
async fn main() -> Result<(), rust_expect::ExpectError> {
let mut session = Session::spawn("echo", &["hello"]).await?;
session.expect("hello").await?;
session.expect_eof().await?;
Ok(())
}§Errors
Returns an error if the session times out before EOF or an I/O error occurs.
Sourcepub async fn expect_eof_timeout(&mut self, timeout: Duration) -> Result<Match>
pub async fn expect_eof_timeout(&mut self, timeout: Duration) -> Result<Match>
Expect end-of-file with a specific timeout.
§Errors
Returns an error if the session times out before EOF or an I/O error occurs.
Sourcepub async fn run_script<I, S>(
&mut self,
commands: I,
prompt: Pattern,
) -> Result<Vec<Match>>
pub async fn run_script<I, S>( &mut self, commands: I, prompt: Pattern, ) -> Result<Vec<Match>>
Run a batch of commands, waiting for the prompt after each.
This is a convenience method for executing multiple shell commands in sequence. For each command, it sends the command line and waits for the prompt pattern to appear.
§Example
use rust_expect::{Session, Pattern};
#[tokio::main]
async fn main() -> Result<(), rust_expect::ExpectError> {
let mut session = Session::spawn("/bin/bash", &[]).await?;
session.expect(Pattern::shell_prompt()).await?;
// Run a batch of commands
let results = session.run_script(
&["pwd", "whoami", "date"],
Pattern::shell_prompt(),
).await?;
for result in &results {
println!("Output: {}", result.before.trim());
}
Ok(())
}§Errors
Returns an error if any command times out or I/O fails.
On error, partial results are lost; consider using Self::run_script_with_results
if you need to capture partial results on failure.
Sourcepub async fn run_script_timeout<I, S>(
&mut self,
commands: I,
prompt: Pattern,
timeout: Duration,
) -> Result<Vec<Match>>
pub async fn run_script_timeout<I, S>( &mut self, commands: I, prompt: Pattern, timeout: Duration, ) -> Result<Vec<Match>>
Run a batch of commands with a specific timeout per command.
Like run_script, but applies the given timeout
to each command individually.
§Errors
Returns an error if any command times out or I/O fails.
Sourcepub async fn run_script_with_results<I, S>(
&mut self,
commands: I,
prompt: Pattern,
) -> (Vec<Match>, Option<ExpectError>)
pub async fn run_script_with_results<I, S>( &mut self, commands: I, prompt: Pattern, ) -> (Vec<Match>, Option<ExpectError>)
Run a batch of commands, collecting results even on failure.
Unlike run_script, this method continues
collecting results and returns them along with any error that occurred.
§Returns
A tuple of (results, error) where:
resultscontains the matches for successfully completed commandserrorisSome(err)if an error occurred,Noneif all commands succeeded
§Example
use rust_expect::{Session, Pattern};
#[tokio::main]
async fn main() -> Result<(), rust_expect::ExpectError> {
let mut session = Session::spawn("/bin/bash", &[]).await?;
session.expect(Pattern::shell_prompt()).await?;
let (results, error) = session.run_script_with_results(
&["pwd", "bad_command", "date"],
Pattern::shell_prompt(),
).await;
println!("Completed {} commands", results.len());
if let Some(e) = error {
eprintln!("Script failed at command {}: {}", results.len(), e);
}
Ok(())
}Source§impl Session<AsyncPty>
impl Session<AsyncPty>
Sourcepub async fn spawn(command: &str, args: &[&str]) -> Result<Self>
pub async fn spawn(command: &str, args: &[&str]) -> Result<Self>
Spawn a new process with the given command.
This creates a new PTY, forks a child process, and returns a Session connected to the child’s terminal.
§Example
use rust_expect::Session;
#[tokio::main]
async fn main() -> Result<(), rust_expect::ExpectError> {
let mut session = Session::spawn("/bin/bash", &[]).await?;
session.expect("$").await?;
session.send_line("echo hello").await?;
session.expect("hello").await?;
Ok(())
}§Errors
Returns an error if:
- The command contains null bytes
- PTY allocation fails
- Fork fails
- The command cannot be executed