iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
Antihost offers Linux VPS plans with full root access, unlimited traffic on a 1 Gbps port and a 14-day free trial.
Use an Expect script when an SSH connection still has to answer interactive prompts—such as a password, keyboard-interactive challenge, or first-connect host-key question. For repeatable unattended jobs, configure SSH public-key authentication first and keep Expect only for the prompts that cannot be removed. A reliable script starts ssh, matches each expected response, sends input, waits for a distinctive remote prompt, and exits with an error on timeout, rejected authentication, or a closed connection.
What Expect adds to SSH automation
Expect is a Tcl extension and program for driving interactive applications. Its model is deliberately small: spawn starts a process, expect watches the process output for patterns, and send supplies the response. That makes it useful for an SSH session that cannot be completed with command-line options alone.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteA normal non-interactive SSH command is preferable when it works. For example, a key-authenticated job can run:
ssh -o BatchMode=yes deploy@vps.example.com 'uname -a'
BatchMode=yes tells the OpenSSH client to fail instead of asking for a password or other input. Expect becomes appropriate when the workflow intentionally includes a prompt, a legacy keyboard-interactive exchange, a one-time host-key confirmation, or a remote program that itself asks questions after login.
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
Expect does not make a password safe merely because the password is inside a script. A password in source code, an argument list, a debug trace, or an accidentally readable file can be recovered. Public-key authentication avoids putting a reusable password in the Expect source and is the better design for a stable unattended connection.
Choose the authentication design before writing the script
| Design | Best use | Credential exposure | Interactive capability | Failure behavior |
|---|---|---|---|---|
| Public-key SSH only | Scheduled jobs and repeatable deployments | Private key stays on the client; no reusable password in the script | Low; unexpected prompts should fail | Use BatchMode=yes and a finite client timeout |
| Expect around SSH | Intentional password, keyboard-interactive, host-key, or legacy prompts | Depends on how secrets are supplied and protected | High; can sequence several prompt/response cycles | Must be implemented with explicit timeout, eof, and authentication-failure branches |
| Hybrid | Key authentication plus one remaining interactive step | Usually lower than password-based login | Handles only the prompt that cannot be eliminated | Keep the Expect state machine as small as possible |
OpenSSH supports public-key, keyboard-interactive, and password authentication. Its documented preference normally tries public key before keyboard-interactive and password. Install and verify key-based access from a second terminal before automating a password. Once key access is confirmed and a recovery path exists, administrators can consider disabling password authentication in the server configuration; do not make that change while your only administrative session depends on the setting being changed.
Prepare the Linux VPS
Install Expect on Ubuntu
On Ubuntu, install the distribution package:
sudo apt update
sudo apt install expect
Ubuntu’s Noble package catalogue lists Expect version 5.45.4-3, with Tcl and tcl-expect as dependencies. Package names and versions vary by distribution, so use the equivalent package manager on a different VPS distribution and verify that the executable is present:
expect -v
command -v expect
The shebang in the script must point to the location returned by the second command. The common path is /usr/bin/expect, but relying on the installed path is safer than assuming it.
Install the OpenSSH client and server when needed
The Ubuntu OpenSSH client is commonly installed by default. If it is missing, install it with:
sudo apt install openssh-client
A machine that accepts incoming SSH connections needs the server package:
Free tools Windows power users keep installed
One-click scans. No signup required.
sudo apt install openssh-server
sudo systemctl enable --now ssh
The client belongs on the machine running the Expect script. The server package belongs on the VPS you are connecting to; installing it is not necessary on a separate managed VPS that already accepts SSH.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
Confirm basic connectivity first
Before adding automation, check the account, hostname, port, firewall, and host key manually:
ssh -p 22 deploy@vps.example.com
Resolve DNS and network failures before debugging Expect. The script can only react to output from an SSH process that actually starts and reaches the server.
Use public-key authentication whenever possible
Create and install a key
Generate a key on the client with ssh-keygen, protect the private key with a passphrase when operationally feasible, and use ssh-agent to make the unlocked key available to the job’s controlled environment. Install only the public key in the destination account’s authorized-key configuration. The private key must not be shared.
After installation, test the exact account and host that the automation will use:
ssh -o BatchMode=yes deploy@vps.example.com 'printf "%sn" connected'
A successful connected response confirms that the job does not need a password prompt. If it fails, inspect the server’s authentication policy, the key file permissions, the agent environment, and the account’s authorized keys before introducing Expect.
When a password is unavoidable
Some legacy systems or provisioning stages expose only a password or keyboard-interactive challenge. Retrieve that secret at runtime from a protected mechanism rather than committing it. Do not put it in source control, command-line arguments, process-visible environment conventions that your threat model does not protect, or diagnostic output. Restrict the script and any temporary secret file to the account that runs the job, and remove temporary material after use.
Expect documents no-echo password collection. If a human must enter the secret, read it with terminal echo disabled and keep the value in memory only as long as necessary. For unattended execution, a protected secret store or a tightly permissioned runtime injection is safer than a literal assignment in the script.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsRank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
A robust Expect script, step by step
Start the process and set a finite timeout
Save the following as ssh-login.exp and make it executable:
#!/usr/bin/expect -f
set timeout 20
set user "deploy"
set host "vps.example.com"
spawn ssh "$user@$host"
expect {
-re {Are you sure you want to continue connecting.*} {
send "yesr"
exp_continue
}
-re {(?i)password:} {
# Supply the password from a protected runtime mechanism.
send "$passwordr"
exp_continue
}
-re {[$#>] $} {
send "uname -ar"
expect -re {[$#>] $}
send "exitr"
}
timeout {
puts stderr "SSH timed out"
exit 1
}
eof {
puts stderr "SSH closed before login"
exit 1
}
}
Run it directly while testing:
chmod 700 ssh-login.exp
./ssh-login.exp
Do not copy the placeholder $password assignment into production. Replace it with a protected runtime mechanism appropriate to the account and scheduler. The example intentionally shows the control flow, not a recommendation to embed a secret.
Understand each part
- Shebang:
#!/usr/bin/expect -fruns the file as an Expect script. Change the path ifcommand -v expectreports another location. set timeout 20: limits how long a pattern wait can block. Choose a value that covers normal network latency without hiding a dead VPS for an unreasonable time.- Variables: keep host, user, port, and other non-secret settings together. Quote values so spaces or Tcl metacharacters do not alter the command.
spawn: starts the SSH client and attaches Expect to its input and output.- Host-key branch: handles the first-connect question only when it actually appears. A previously trusted host should not ask it again unless the known-hosts state changed.
- Password branch: matches case-insensitively and sends a carriage return. For keyboard-interactive authentication, add branches for the exact prompts emitted by the installed SSH and server configuration.
- Prompt branch: waits for a shell prompt before sending a command. The regular expression is deliberately generic for illustration; make yours distinctive for the target account and shell.
exp_continue: returns to the same expectation block after a host-key or authentication response, allowing another prompt in the sequence.timeoutandeof: write context to standard error and return status 1 so a scheduler or calling program can detect failure.
Handle host keys without weakening verification
A first connection may print a question such as “Are you sure you want to continue connecting?” The safe automation pattern is to verify the server’s host key out of band, then accept it or pre-populate the client’s known-hosts file. Blindly answering yes to any first-connect prompt defeats the protection against connecting to the wrong machine.
Do not use options that turn off host-key checking merely to make an Expect script pass. If the server’s key changes unexpectedly, stop and investigate rather than teaching the script to accept the change. Keep the host-key branch narrowly matched to the complete prompt used by the installed OpenSSH version; a broad match can consume unrelated output.
Match prompts precisely
Shell prompts
Expect patterns are unanchored unless you anchor them. Regular expressions use the -re switch. A pattern such as [$#>] $ looks for a final prompt character followed by a space, but ordinary command output can contain the same characters. Set a distinctive prompt for the automation account or command session when possible, then match that exact marker.
send "PS1='EXPECT_READY> '
"
expect "EXPECT_READY> "
send "uname -a
"
expect "EXPECT_READY> "
Only use a prompt change when the account’s shell accepts it and the command cannot be intercepted by an unexpected startup script. If the login shell prints banners, warnings, or profile output, allow for those lines before waiting for the marker.
Authentication and keyboard-interactive prompts
Different servers can label a challenge as Password:, Verification code:, or another text. Match the exact prompt and send the corresponding response. Never assume that one response is valid for every challenge. If several prompts can repeat, keep them in one expect block and use exp_continue only for known, finite stages.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Failure text
Add explicit branches for authentication rejection and connection errors instead of letting the script wait until timeout:
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
expect {
-re {Permission denied} {
puts stderr "SSH authentication failed"
exit 2
}
-re {Could not resolve hostname|Connection refused|No route to host} {
puts stderr "SSH connection failed"
exit 3
}
timeout {
puts stderr "SSH timed out"
exit 4
}
eof {
puts stderr "SSH ended before the expected prompt"
exit 5
}
}
Keep the expressions compatible with the OpenSSH version and locale used by the VPS. If localized messages are possible, prefer a stable prompt or inspect the SSH exit status where practical.
Run commands safely after login
Send one command, wait for the known prompt, and only then send the next command. Quote shell arguments before they reach the remote shell; Tcl quoting protects the local script, not the remote command language. For a fixed command sequence:
expect "EXPECT_READY> "
send "mkdir -p -- /srv/appr"
expect "EXPECT_READY> "
send "printf '%s\n' deployedr"
expect "EXPECT_READY> "
send "exitr"
expect eof
A command can fail while the shell remains open, so prompt detection alone does not prove success. For important operations, have the remote command emit a clear success marker only after it succeeds, or execute a remote wrapper that returns a meaningful exit status. Capture output for diagnosis without recording passwords, private keys, or unrelated sensitive data.
Prefer a single, well-quoted non-interactive SSH command when the remote operation does not truly require a session. Fewer prompt transitions mean fewer ways for banners, errors, or shell differences to confuse the state machine.
Make unattended execution predictable
Scheduler and service behavior
- Use an absolute path to the script, the SSH binary, and any secret-provider command.
- Set a finite Expect timeout and, where appropriate, an SSH connection timeout such as
-o ConnectTimeout=15. - Return non-zero status for every authentication, network, timeout, and unexpected-end condition.
- Prevent overlapping runs if the job changes remote state; use the scheduler’s locking facility or an equivalent lock.
- Define the working directory, locale, and environment explicitly. Do not assume an interactive shell profile is loaded.
- Send concise status and error context to the scheduler’s log, excluding credentials and sensitive command output.
Use BatchMode for key-only jobs
If the final design uses only a key, remove Expect and run SSH with -o BatchMode=yes. If Expect remains around a key-authenticated session for a later interactive program, keep authentication branches that fail clearly rather than silently waiting for a password that should never be requested.
Protect files and processes
Store the script in a directory writable only by the job account and administrators, and use restrictive permissions such as mode 700 when the file contains operational details. Do not print the Expect buffer wholesale in a troubleshooting mode: it can contain usernames, challenge text, command output, and accidental secrets. Review process listings and scheduler configuration to ensure a password is not exposed as an argument.
Test in a controlled order
- Manual network test: connect with ordinary
sshand confirm DNS, routing, port access, and the expected host key. - Manual authentication test: verify the intended key, password, or keyboard-interactive policy with the exact account.
- Script syntax test: run
expect -c 'source ./ssh-login.exp'or execute the file directly and correct Tcl quoting errors. - First-connect test: use a controlled known-hosts location if you need to exercise the host-key branch; verify the key before accepting it.
- Failure tests: deliberately use an unavailable hostname, wrong account, and invalid credential in a non-production account. Confirm each case exits non-zero and does not hang.
- Prompt tests: test with the real shell, banners, locale, and startup files. Ensure command output cannot be mistaken for the prompt.
- Scheduler test: run under the same service account and environment used in production, then inspect logs for status without exposing secrets.
Keep an alternate administrative session open while changing SSH server authentication settings. Test from a non-production account first, and retain a recovery path before disabling any method.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Troubleshoot the common failure modes
| Symptom | Likely cause | Correction |
|---|---|---|
| Expect reports a timeout before any prompt | DNS, firewall, wrong port, unavailable VPS, or an SSH client waiting for a condition the script does not match | Run manual SSH, verify the host and port, add a finite connection timeout, and inspect the exact client output |
| Authentication is rejected | Wrong account or secret, missing authorized key, disabled method, or an unhandled keyboard-interactive challenge | Authenticate manually, verify server policy and key installation, then add only the exact required prompt branch |
| Script accepts a host key unexpectedly | Known-hosts state is absent or the host-key branch is too broad | Verify the key out of band, pre-populate known hosts, and narrow the match; never disable verification |
| Commands are sent before login completes | Prompt expression matches a banner or ordinary output | Use a distinctive, anchored prompt marker and wait for it after every command |
| Script hangs after a failed command | No timeout, no failure branch, or command output lacks the expected prompt | Set timeout, handle eof, check a success marker or exit status, and capture limited diagnostic context |
| Works interactively but fails in cron or a service | Different PATH, HOME, permissions, agent socket, locale, or working directory | Use absolute paths, define the environment, make the key/agent available to that account, and test under the scheduler identity |
When to replace Expect with a simpler design
Replace an Expect wrapper with ordinary SSH when the server can use public-key authentication and the remote command can run non-interactively. This reduces code, secret handling, prompt fragility, and maintenance. Keep Expect when the prompt is a real protocol requirement that you cannot remove, when a legacy workflow must be driven, or when a controlled interactive exchange is the only supported interface.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
For a two-option decision, compare the designs on five questions:
- Credential exposure: can a key and agent replace a reusable password?
- Interactive requirement: does the server or remote program genuinely ask for input?
- Maintainability: will shell banners, locales, and software upgrades change the matched text?
- Failure detection: does the caller receive a reliable non-zero status for every failure path?
- Policy compatibility: does the server permit the selected authentication method and host-key handling?
The smallest design that satisfies those questions is usually the safest one.
Reference material for learning Expect
The Expect manual describes the language’s pattern matching, spawn, send, timeouts, end-of-file handling, no-echo password collection, regular expressions, and exp_continue. The Linux expect(1) manual characterizes Expect as a program that “talks” to interactive programs according to a script. Don Libes’s Exploring Expect is identified by the Expect manual as the best introduction to the language and is a useful deeper reference when a short SSH wrapper grows into a larger state machine.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Practical final checklist
- Expect is installed from the VPS distribution repository and the shebang matches its actual path.
- The OpenSSH client is present, and the destination has an SSH server only when it must accept incoming connections.
- Public-key authentication was tested first; the private key remains private and is protected.
- Any unavoidable password or challenge response comes from a protected runtime mechanism, never committed source or debug output.
- Host-key acceptance is verified, not blindly bypassed.
- Every prompt branch is specific, the shell prompt is distinctive, and commands are sent only after the expected prompt.
- Timeout, authentication failure, connection failure, and
eofpaths return non-zero statuses. - Scheduler execution uses absolute paths and the correct account, environment, permissions, and agent access.
- Logs contain enough status to diagnose a failure but never contain passwords, private keys, or unnecessary sensitive output.
Frequently Asked Questions
Can an Expect script log in with an SSH password?
Yes, if the server permits password or keyboard-interactive authentication, but retrieve the secret through a protected runtime mechanism. Public-key authentication is safer for unattended jobs because it avoids placing a reusable password in the script.
Why does my Expect script hang instead of failing?
A pattern wait has no effective timeout or no branch for a closed connection, authentication failure, or changed prompt. Set a finite timeout and handle timeout and eof explicitly.
Should I automatically answer the SSH host-key question with yes?
Only after verifying the server’s host key through a trusted channel. Do not disable host-key checking or accept an unexpected key change just to make automation succeed.
Is Expect required for SSH key authentication?
No. A key-authenticated command can normally use ordinary SSH, often with -o BatchMode=yes. Expect is justified when another interactive exchange remains.
Recommended Free Tools
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

