Created
October 16, 2022 14:23
-
-
Save mietzen/bcd5ff2ce5f5c167db076f2864e72675 to your computer and use it in GitHub Desktop.
Change your ssh pub key on all systems
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash -xe | |
NEW_PUB_KEY="$HOME/.ssh/id_ed25519.pub" | |
OLD_PUB_KEY="$HOME/.ssh/id_rsa.pub" | |
NEW_PUB_KEY_STR=$(cat ${NEW_PUB_KEY}) | |
OLD_PUB_KEY_STR=$(cat ${OLD_PUB_KEY} | cut -d' ' -f2) | |
for IP in $(cat ip-list-ssh.txt); do | |
# Backup authorized_keys | |
ssh ${USER}@${IP} "cp ~/.ssh/authorized_keys{,.bak}" | |
# Add new key to authorized_keys | |
ssh ${USER}@${IP} "echo ${NEW_PUB_KEY_STR} >> ~/.ssh/authorized_keys" | |
# Test new key | |
if ssh -o IdentitiesOnly=yes -i ${NEW_PUB_KEY} ${USER}@${IP} 'exit'; then | |
# Remove old key (with or without comments) | |
ssh ${USER}@${IP} "grep -v '${OLD_PUB_KEY_STR}' ~/.ssh/authorized_keys > /tmp/authorized_keys" | |
ssh ${USER}@${IP} "mv /tmp/authorized_keys ~/.ssh/authorized_keys" | |
else | |
echo "FAILED: ${USER}@${IP}" | |
ssh ${USER}@${IP} "mv ~/.ssh/authorized_keys{.bak,}" | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Create a
ip-list-ssh.txt
with e.g.nmap 192.168.1.0/24 -Pn -p 22 --open -oG - | grep "/open" | awk '{ print $2 }' > ip-list-ssh.txt
Than run
bash -xe ./change_ssh_pub_key.sh