Copy ssh public key to multiple Linux hosts
With this simple loop you can automate it and spread to all remote servers.
#!/bin/bash
for ip in `cat /home/list_of_servers`; do
ssh-copy-id -i ~/.ssh/id_rsa.pub $ip
done
Here is my simple script to copy ssh-keygen to multiple servers without asking password everytime.
for server in `cat server.txt`;
do
sshpass -p "password" ssh-copy-id -i ~/.ssh/id_rsa.pub user@$server
done
This requires sshpass, which may need to be installed separately, either via package or from source.
The accepted answer won't work if one needs to put someone else's public key to multiple machines. So, I've come up with the following solution:
cat add-vassal-tc-agents.sh
#!/bin/bash
set -x # enable bash debug mode
if [ -s vassal-public-key.pub ]; then # if file exists and not empty
for ip in `cat tc-agents-list.txt`; do # for each line from the file
# add EOL to the end of the file and echo it into ssh, where it is added to the authorized_keys
sed -e '$s/$/\n/' -s vassal-public-key.pub | ssh $ip 'cat >> ~/.ssh/authorized_keys'
done
else
echo "Put new vassal public key into ./vassal-public-key.pub to add it to tc-agents-list.txt hosts"
fi
This script adds the new key to the users on the list of machines, provided that the environment it is run on has the access.
Example of tc-agents-list.txt
:
[email protected]
[email protected]
[email protected]
[email protected]