One-Command SSH Password to Key Pair Migration

Previously, when setting up a Kubernetes cluster on vSphere, all nodes were cloned from a single CentOS template. This meant every node shared the same password — which is not particularly secure. So I decided to disable password-based SSH login across all nodes.

Here is the script I wrote:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/bash -e

cd $(dirname $0)/..

IPS=("192.168.0.120" "192.168.0.238" "192.168.0.134" "192.168.0.122" "192.168.0.162" "192.168.0.159")

for ip in $IPS[*];
do
ssh-keygen -f "ssh/id_rsa_${ip}" -t rsa -N ''
sshpass -e ssh-copy-id -o "StrictHostKeyChecking no" -i "ssh/id_rsa_${ip}" root@$ip -f
ssh -i ssh/id_rsa root@$ip <<'ENDSSH'
sed -i 's/^PasswordAuthentication\s*yes$/PasswordAuthentication no/g' /etc/ssh/sshd_config
service sshd restart
ENDSSH
done

Before running this script, you need to install sshpass and run export SSHPASS=YOUR_PASSWAORD.