Operations 3 min read

Automate Multi-Server Commands with Expect: A Quick Guide

This article introduces the Expect scripting language, an extension of Tcl, and provides a concise example that automates running commands on multiple Linux servers by handling interactive prompts such as password entry, along with usage instructions and installation tips for CentOS and Ubuntu.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Automate Multi-Server Commands with Expect: A Quick Guide

Recently, through the book "exploring expect", I learned the Expect scripting language, an extension of Tcl, used to solve automation problems where tools cannot interact automatically, such as providing a password during SSH login.

#!/usr/bin/expect
#purpose:auto run command on multiple servers
#how to:  mms <user> <cmd>
#write by zhumaohai.
#blog:http://www.centos.bz/
if {$argc < 2} {
    puts "usage: mms <user> <cmd>"
    exit 1
}
#set servers
set SERVERS {"192.168.0.100" "192.168.0.101" "192.168.0.102"}
#set password
set PASSWORDS(user1) "passwd1"
set PASSWORDS(user2) "passwd2"
#get variables
set USER [lindex $argv 0]
set CMD [lrange $argv 1 end]
set passwd $PASSWORDS($USER)
foreach x $SERVERS {
    eval spawn ssh -l $USER $x $CMD
    expect {
        "password" { send "$passwd\r" }
        "yes/no" { send "yes\r"; exp_continue; }
    }
    expect eof
}

The script defines three servers (192.168.0.100, 192.168.0.101, 192.168.0.102) and passwords for users user1 and user2; save the script as ms and run it as ./ms user1 date to execute the date command on all servers. Ensure the expect package is installed (e.g., yum install expect on CentOS or apt-get install expect on Ubuntu).

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

LinuxSSHexpect
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.