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
- the password is the same for all 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
- grep -i ‘.’: maybe you dont need this, but i need it in my case, because i wanted to filter only lines with a dot, every ipv4 address has a dot
- grep -v ‘#\|:’: you might need this! in my case i wanted to filter out comments and ipv6 addresses
- awk ‘{ print $2 }’: get only the host name
- xargs -I{}: pass as positional parameter each host name
- sshpass -p password ssh-copy-id username@{} -p 22: use sshpass in order to avoid entering the password each time, did you notticed ‘{}’ this will replaced by each hostname
I hope you found my article useful :)