Operations 3 min read

Bash Script for Key‑Based Multi‑Host SSH Access

This Bash script automates key‑based SSH authentication across multiple hosts by scanning a subnet, generating a key pair, installing sshpass, copying the public key and known_hosts file to each reachable machine, and ensuring password‑less login for subsequent connections.

Practical DevOps Architecture
Practical DevOps Architecture
Practical DevOps Architecture
Bash Script for Key‑Based Multi‑Host SSH Access

This article provides a complete Bash script that enables password‑less SSH access to multiple Linux hosts using key authentication.

First, the script defines a password and the target subnet range, then discovers live IP addresses by pinging each address from the third to the last host in the subnet.

#!/bin/bash
PASS=123456
# 设置网段最后的地址
END=254
IP=`ip a s eth0 | awk -F '[ /]+ ' 'NR==3{print $3}'`
NET=${IP%.*}.
rm -f /root/.ssh/id_rsa
[ -e ./SCANIP.log ] && rm -f SCANIP.log
for((i=3;i<="$END";i++));do
ping -c 1 -w 1 ${NET}$i &> /dev/null && echo "${NET}$i" >> SCANIP.log &
done
wait

After discovering live hosts, the script generates an SSH key pair without a passphrase and ensures the sshpass utility is installed.

ssh-keygen -P "" -f /root/.ssh/id_rsa
rpm -q sshpass || yum -y install sshpass

It then copies the generated public key to each discovered host, enabling password‑less login.

sshpass -p $PASS ssh-copy-id -o StrictHostKeyChecking=no $IP
AliveIP=(`cat SCANIP.log`)
for n in ${AliveIP[*]};do
sshpass -p $PASS scp -o StrictHostKeyChecking=no -r /root/.ssh root@${n}:
done

Finally, the script distributes the .ssh/known_hosts file to all hosts so that the first mutual connection does not require manual confirmation.

# 把 .ssh/known_hosts 拷贝到所有主机,使它们第一次互相访问时不需要输入回车
for n in ${AliveIP[*]};do
scp /root/.ssh/known_hosts ${n}:.ssh/
done

The script concludes with a separator line indicating the end of the procedure.

----------------------end---------------------
automationOperationsbashSSHkey-authenticationmulti-host
Practical DevOps Architecture
Written by

Practical DevOps Architecture

Hands‑on DevOps operations using Docker, K8s, Jenkins, and Ansible—empowering ops professionals to grow together through sharing, discussion, knowledge consolidation, and continuous improvement.

0 followers
Reader feedback

How this landed with the community

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