bash tricks: how to copy ssh key to all /etc/host entries with an one-liner

Scenario: you have just landed to a company which does not have a an automation tool to copy your key to all hosts, to make things worse the hosts are more than 500, what do you do?

Some hints

  • the resolving of the hosts is not done by a DNS, but using /etc/hosts

Modify /etc/ssh/ssh_config

open with sudo the /etc/ssh/ssh_config file and change “StrictHostKeyChecking yes” to “StrictHostKeyChecking no”

The one-liner

The actual task is done by this one-liner

$ cat /etc/hosts | grep -i '.' | grep -v '#\|:' | awk '{ print $2}' | xargs -I{} sshpass -p password ssh-copy-id username@{} -p 22

Explaination of the commands:

  • cat /etc/hosts: prints the contents of the file to stdout

I hope you found my article useful :)

Written by

DevOps engineer, loves Linux, Python, cats and Amiga computers

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store