Shell – Copy ssh public key to multiple Linux hosts

shell-scriptssh

I am trying to copy .ssh/id_rsa.pub from our central server to multiple servers. I have the following script which I usually use to push changes to the different servers.

#!/bin/bash


for ip in $(<IPs); do
    # Tell the remote server to start bash, but since its
    # standard input is not a TTY it will start bash in
    # noninteractive mode.
    ssh -q "$ip" bash <<-'EOF'



EOF

done

But in this case, I need to cat the public key on the local server and then add that to multiple servers. Is there a way by using the above here document script to execute the following.

cat .ssh/id_rsa.pub |ssh tony@0.0.0.0 'cat > .ssh/authorized_keys'

Best Answer

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
Related Question