Automate Bulk Linux Root Password Changes with Expect Scripts
Learn how to efficiently update root passwords across dozens or hundreds of Linux servers by creating Expect scripts that automate SSH logins, parse IP and password lists, and execute batch password changes, complete with step-by-step instructions, required environment setup, and script explanations.
Background
Changing a Linux system password can be done with the passwd command, but updating hundreds of servers manually via SSH is time‑consuming. Using Expect to automate the process enables fast bulk password changes.
Environment Preparation
Requirements: a Linux environment with tcl and expect installed.
Check if they are present; if not, install with yum -y install expect tcl.
Experiment note: This article uses Expect’s automated interaction to log into remote servers and change passwords in bulk.
Specific Steps
Example: bulk root password change
1. Create script files
Three files are needed:
touch ~/ip.txt
This file stores target server IP addresses and root passwords.
touch ~/passwd.sh
Uses a for loop to execute the Expect script for each server.
touch ~/action.exp
Contains Expect code that handles the interactive SSH session.
Note: The first line #!/bin/expect tells the system to run the script with the Expect interpreter; line 11 sets the new password to 123456.
2. Add execution permission
Make the scripts executable (e.g., chmod +x passwd.sh action.exp).
3. Run the batch change
Execute sh passwd.sh to apply the new password to all listed servers.
Script Explanation
passwd.sh reads ip.txt, extracts each server’s IP and root password, and passes them to the Expect script via a for loop.
action.exp details:
The shebang #!/bin/expect selects the Expect interpreter.
Lines 2‑3 retrieve the IP address and password passed from the Bash script using [lindex $argv n].
Line 4 sets the overall timeout (seconds).
Line 5 uses spawn to start an SSH session.
Lines 6‑9 use expect blocks to automatically answer prompts: “yes/no” and “password”.
Line 11 changes the remote password to 123456 after login.
Lines 12‑13 use expect eof and spawn to close the session cleanly.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Linux
Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
