expect-ruby
A Ruby library for automating interactive programs through POSIX pseudo-terminals. Start a child process, wait for text or regular expressions, send input, and manage timeouts, callbacks, and cleanup with Ruby objects and blocks.
RubyGems package: expect-pty. Requires Ruby 4.0.6+ on Linux or macOS.
Install
Add the gem to your Gemfile:
gem "expect-pty", require: "expect/pty"Then run bundle install, or install it directly with gem install expect-pty.
Quick start
require "expect/pty"
program = "STDOUT.sync = true; print 'ready>'; STDIN.gets; puts 'done'"
Expect.spawn("ruby", "-e", program) do |session|
prompt = session.expect("ready>", timeout: 5)
raise "child did not become ready" unless prompt.matched?
session.puts("continue")
result = session.expect("done", timeout: 5)
puts result.match if result.matched?
endThe block closes the session and reaps its child process, including when the block raises. Commands execute directly with separate argv entries, including a single executable string. Shell syntax requires explicit shell: true with one command string; never pass untrusted input into that string.
Features
- Reusable automatic response rules for repeated confirmations, paging, and dynamic replies.
- Exact byte-string and Ruby Regexp matching, immutable results, callbacks, timeouts, and EOF handling.
- Explicit PTY sessions or borrowed IO sessions, with scoped cleanup and process status.
- Multi-session waits, IO forwarding, and interactive terminal handoff.
- Optional Logger diagnostics, receive transcripts, and streaming redaction.
Documentation
In a repository checkout, run the test suite and package checks with script/ci. The suite uses local PTYs, pipes, and sockets; SSH credentials are not required.
Licensed under the MIT License. Contributions are welcome in English or Chinese; see CONTRIBUTING.md.