Working with ssh keys on Linux servers/cluster

If you’ve Linux servers/cluster and for each user you need to have ssh key for password-less access to different nodes, below script might be useful or be a small hint on what you might be able to get.


Scenario which I made below script is a cluster of Linux servers running distributed computing application and users need to have ssh key so they can create job and job scheduler can connect to all nodes with their keys and not ask for password. in this scenario, server have pattern base naming which make it easier for automation.

Assumption is that the user profile mounted to all nodes or other solution has been used to sync any changes in user home on all nodes.

This script will check if user has ssh key, if not, it’ll create one (line 10).
Next, it’ll check for ‘authorized_keys’, if not exist, it’ll create and set required permission (line 11 & 12).
And it’ll create backup of current ‘known_hosts’ (line 14).
Finally, it’ll add check if each node in cluster information already exist in known_hosts, if not it’ll add fingerprint based on both name and IP to the known_hosts list for password-less connection (line 16-30)

#!/bin/bash
###
# Keymaker - v0.2
# by: Sohrab Kasraeianfard
# This script will check if user has ssh key, if not, it'll create one.
# Next, it'll check for 'authorized_keys', if not exist, it'll create and set required permission
# And finally it'll create backup of current 'known_hosts' and add node in cluster to the list for password-less connection
###

test -f "$HOME/.ssh/id_rsa" && test -f "$HOME/.ssh/id_rsa.pub" || ssh-keygen -t rsa -b 4096 -f "$HOME/.ssh/id_rsa" -q -N ""
test -f "$HOME/.ssh/authorized_keys" || cp "$HOME/.ssh/id_rsa.pub" "$HOME/.ssh/authorized_keys"
chmod 700 "$HOME/.ssh/authorized_keys"

test -f "$HOME/.ssh/known_hosts" && cp "$HOME/.ssh/known_hosts" "$HOME/.ssh/known_hosts.old_$(date +'%Y%m%d')"

printf "===== Working on key for master =====\n"
grep -q "master_node" "$HOME/.ssh/known_hosts" || ssh-keyscan master_node >> $HOME/.ssh/known_hosts
grep -q "AAA.BBB.CCC.1" "$HOME/.ssh/known_hosts" || ssh-keyscan AAA.BBB.CCC.1 >> $HOME/.ssh/known_hosts

for node in {2..13}
do
printf "===== Working on key for node$node =====\n"
grep -q "node$node" "$HOME/.ssh/known_hosts" || ssh-keyscan node$node >> $HOME/.ssh/known_hosts
grep -q "AAA.BBB.CCC.$node" "$HOME/.ssh/known_hosts" || ssh-keyscan AAA.BBB.CCC.$node >> $HOME/.ssh/known_hosts
done

It's your kindness to leave a reply/feedback