An Expect script can automate an interactive SSH login by responding to prompts, then run commands on a Linux VPS. You will need Expect and an SSH account; for routine unattended access, SSH keys are safer and simpler, so use password automation only when you have a specific need and can protect the password.
What You’ll Need
- A Linux computer where you can install Expect and run the script.
- The VPS hostname or IP address, SSH username, and a working login method.
- Permission to connect to the VPS and, if needed, install packages on your local computer.
- A secure way to store any password the script must use. Avoid putting a real password directly in the script.
Step-by-Step
- Check whether Expect is installed. On the computer that will run the automation, enter
expect -v. If the shell reports that the command is missing, install Expect using your distribution’s package manager. For Debian or Ubuntu, runsudo apt update, thensudo apt install expect. On Fedora, usesudo dnf install expect. Package names and commands can vary on other systems. - Confirm ordinary SSH works first. Try
ssh username@your-vps-host, replacing the example values. Resolve connection, account, or host-key prompts interactively before automating. On first connection, compare the displayed host-key fingerprint with one obtained through a trusted channel, then accept it only if it matches. Do not disable host-key checking to make a script run. - Create a private script file. Use
nano ssh-task.expor another editor to create a file. Start it with this template, replacing the host and username:
#!/usr/bin/expect -f
set timeout 30
set host "your-vps-host"
set user "your-username"
spawn ssh "$user@$host"
expect {
-re "Are you sure you want to continue connecting.*" {
send_user "Verify the host fingerprint before accepting it.\n"
exit 1
}
-re "(?i)password:" {
send_user "Password login was requested; no password is stored in this template.\n"
exit 1
}
timeout {
send_user "Timed out waiting for SSH.\n"
exit 1
}
eof {
send_user "SSH ended before a login prompt appeared.\n"
exit 1
}
"*\$ " {}
"*# " {}
}
- Choose a safe authentication method. Prefer an SSH key: create one with
ssh-keygenif you do not already have a suitable key, and install its public key on the VPS using your provider’s instructions orssh-copy-id username@your-vps-hostwhere supported. Protect the private key with appropriate file permissions and a passphrase; use an SSH agent to unlock it when automation runs interactively. Expect can then automate a session without embedding an account password. - Add the interaction your task needs. The template stops if it sees a password prompt. That is intentional: a prompt can mean a key is missing, rejected, or unavailable. Once key-based login works, replace the example prompt handling with the actual command and expected response. For a one-off remote command, the simpler and usually more reliable option is to call SSH directly, such as
ssh username@your-vps-host 'uptime'; Expect is most useful when a program genuinely requires interactive responses. - Match prompts carefully. Expect waits for text from the spawned process. Add patterns for the prompts your specific remote program produces, followed by
sendcommands. For example, after login,expect -re {\$ $}can wait for a typical shell prompt andsend -- "uptime\r"can enter a command. Shell prompts vary, so test your pattern against the actual output. Avoid broad patterns that might match an unrelated message. - Finish the session and check its result. After sending a command, wait for its expected output or prompt, then send
exit\rand wait foreof. Set a finite timeout for each expected interaction, and print clear error messages when a wait expires. A successful SSH connection alone does not prove the remote command succeeded; capture or inspect its output and exit status where the task requires it. - Set permissions and test manually. Save the file, then run
chmod 700 ssh-task.expand./ssh-task.exp. The first run should be observed at a terminal. Check that it connects to the intended host, responds only to expected prompts, runs the intended command, and exits cleanly. Do not schedule it until those checks pass. - Schedule only a noninteractive, reviewed task. For a repeated job, consider a cron entry or systemd timer, with explicit paths and logging. Cron does not share your normal terminal or agent environment automatically; configure access to the key or agent securely. Keep logs free of passwords, tokens, and private data, and make failures visible rather than silently ignoring them.
Common Mistakes
- Hard-coding a password: Scripts may be readable through backups, source control, or incorrect file permissions. Prefer keys. If password-based automation is unavoidable, use an approved secret store or protected runtime input, restrict access, and rotate exposed credentials.
- Accepting every host key automatically: This removes an important identity check and can expose the connection to interception. Verify the fingerprint out of band and keep normal SSH host-key checking enabled.
- Assuming one prompt format: Prompts differ by shell, locale, SSH configuration, and server policy. Test the exact patterns and make unexpected output stop the script.
- Using Expect for a simple command: A direct SSH command is easier to quote, monitor, and schedule when no interactive prompt is involved.
- Leaving a session open: Send an explicit exit and wait for the process to end. Otherwise scripts can hang, time out, or leave remote work running unexpectedly.
Tips
- Use
spawn ssh -o BatchMode=yes user@hostfor key-based jobs that should fail rather than ask for a password or passphrase. This option does not bypass host-key verification. - Keep hostnames, usernames, command arguments, and timeouts in clearly named variables. Quote values and use
send --when sending text that might begin with a dash. - Test with a harmless command such as
uptimebefore automating changes. Log status and useful error messages, but never log credentials. - For scheduled work, consider a dedicated VPS account with only the permissions the task needs. Restrict access to the script and any key material.
Troubleshooting
If the script times out, run the same SSH command manually and check network access, DNS, firewall rules, and the VPS’s SSH service. Increase the timeout only if the delay is expected; an indefinite wait can hide a real failure. If Expect reports that it cannot find a prompt, inspect the exact terminal output and adjust the pattern rather than guessing. You can temporarily add exp_internal 1 near the top of the script to trace matching; remove it after debugging because verbose traces may reveal sensitive session output.
If login works manually but fails in a scheduled job, check the job’s environment, working directory, key path, permissions, and SSH agent availability. Use absolute paths and test under the same user that runs the job. If SSH asks to verify a host key, verify the fingerprint and add it through a normal trusted SSH connection; do not make the script accept an unknown key. If authentication fails, use SSH’s diagnostic output with ssh -v to identify whether the key is offered and accepted, and fix the SSH configuration or authorized key on the server.
Frequently Asked Questions
Is Expect safe for storing an SSH password?
It is risky to place a password in a script or command line. Prefer SSH keys; if a password is required, use a secure secret-management method and limit who can access it.
Can Expect automate SSH without a password?
Yes. Configure key-based authentication and let Expect handle any remaining interactive steps. For a simple remote command, ordinary SSH may be enough.
Does this script run on the VPS?
Usually it runs on the computer initiating the connection. Install Expect there; the VPS only needs to accept SSH connections and run the remote commands.
Can I run an Expect script from cron?
Yes, but scheduled jobs have a limited environment and no interactive terminal. Use key authentication, explicit paths, finite timeouts, and logging that excludes secrets.
Why does the script hang after login?
It may be waiting for a prompt pattern that does not match the server’s shell, or it may not send an exit command. Inspect the output, refine the pattern, and explicitly close the session.
Should I turn off SSH host-key checking?
No. Verify the server fingerprint and retain SSH’s normal host-key checks. Automatically trusting an unknown key weakens protection against connecting to an impostor host.
Related
General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.
More in this bed
- Access to Compressed Zipped Folder Is Denied in Windows 10
- Erase Microsoft Surface Data Without Booting Windows
- Apps to Install for a New Mac: A Practical Starter List
- Show or Hide Thumbnails in Windows 10
- Choose a Loud Bluetooth Speaker for Your Gathering
- iPhone X IMEI and Serial Number: How to Find Them