Operations 14 min read

Automate SSH Key Distribution and Batch Operations with Expect, PSSH, and PSCP

This guide details how to automate SSH key generation, password‑less login, and batch file distribution across hundreds of servers using Expect scripts, ssh‑keygen, ssh‑copy‑id, and the pssh/pscp/pslurp command suite, providing step‑by‑step examples for efficient operations.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Automate SSH Key Distribution and Batch Operations with Expect, PSSH, and PSCP

1. Script Background

In enterprises, small clusters of servers often require repetitive tasks such as updating SSH public keys or backing up /etc/passwd on hundreds of machines. When dedicated automation tools like Ansible are unavailable, scripts can automate these tasks, especially for actions repeated more than three times.

2. Technical Requirements

2.1 SSH Password‑less Authentication

Two authentication methods are described: symmetric encryption (e.g., DES, 3DES, AES) and asymmetric encryption (RSA, DSA). The latter uses a key pair where the public key encrypts data and the private key decrypts it.

ssh passwordless login principle
ssh passwordless login principle

The ssh-keygen command generates a key pair. Example:

[root@centos7 ~]# ssh-keygen -t rsa -f .ssh/id_rsa
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in .ssh/id_rsa.
Your public key has been saved in .ssh/id_rsa.pub.

After generation, ssh-copy-id -i .ssh/id_rsa.pub user@host uploads the public key to the remote host, enabling password‑less login.

2.2 Distributing Keys with Expect

When dealing with hundreds of servers, manually entering keys is impractical. Expect scripts automate the interaction with ssh-copy-id to distribute keys without manual password entry.

2.3 pssh Family Commands

The pssh suite (pssh, pscp, pslurp) allows parallel execution, file copying, and file retrieval across multiple hosts. Important notes: variable and wildcard expansion is not supported in command arguments unless the -A option forces password authentication.

Key options for pssh include: -h: host list file -H: specify hosts directly -i: display output on the terminal -o: directory for standard output -e: directory for error output -l: login user -A: enable password authentication

Example to disable SELinux on multiple hosts:

pssh -H [email protected] -i "sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config"

Similar options exist for pscp (parallel scp) and pslurp (parallel download), with flags such as -v (verbose), -a (preserve attributes), -r (recursive), and -L (local destination for downloads).

3. Script Implementation Process

3.1 Environment

The scripts target a CentOS 7 environment managing roughly a hundred servers. For larger clusters, tools like Ansible are recommended.

3.2 Functionality

The automation script performs:

Batch command execution with result logging.

Batch file upload to remote hosts.

Batch file download from remote hosts.

3.3 Development Steps

Generate SSH keys and use Expect to distribute the public key.

Upload the business script to all hosts using pscp.pssh.

Execute the script remotely via pssh.

Collect logs and results with pslurp.pssh for further processing.

3.4 Example Scripts

Expect script to send a public key:

#!/bin/expect
if { $argc != 2 } {
    send_user "usage: send-rsa-id file host 
"
    exit
}
set password wbxue.blog
set file [lindex $argv 0]
set ip [lindex $argv 1]
spawn ssh-copy-id -i $file root@$ip
expect {
    "yes/no" {send "yes\r"; exp_continue}
    "*password*" {send "$password\r"}
}
expect eof

Bash wrapper to call the Expect script for a range of IPs:

#!/bin/bash
file=/root/.ssh/id_rsa.pub
net=192.168.100
for n in {1..255}; do
    ip=$net.$n
    expect send-rsa-pub.exp $file $ip
done

Sample business script that checks disk usage and logs warnings:

#!/bin/bash
>/var/log/diskcheck.log
df | grep "/dev/sd" | while read disk; do
    diskused=`echo $disk | sed -r 's/.* ([0-9]+)%.*/\1/'`
    devname=`echo $disk | cut -d " " -f1`
    [ $diskused -ge 1 ] && echo "$devname will be full:$diskused%" >> /var/log/diskcheck.log
done

Deploy and run the script, then retrieve the log:

# Upload script
pscp.pssh -H 192.168.100.128 /root/diskcheck.sh /app/
# Execute script
pssh -H [email protected] -i bash /app/diskcheck.sh
# Retrieve log
pslurp -H 192.168.100.128 -L /app/ /var/log/diskcheck.log diskcheck.log

4. Conclusion

Using Expect, ssh‑keygen, and the pssh suite enables efficient, password‑less automation for managing dozens or hundreds of Linux servers, reducing manual effort and improving operational reliability.

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.

LinuxBatchSSHexpectpssh
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.