Skip to content

SSH Key adding

  • Assuming you already have key setup for your machine.
#!/bin/bash

hostlist=( 'alpha.lan' 'beta.lan' 'gamma.lan' 'delta.lan' 'epsilon.lan' )
# get number of elements in the array
chost=${#hostlist[@]}


for (( i=0;i<$chost;i++)); do
    echo ${hostlist[${i}]}
    file=`cat /dev/urandom|od -N4 -An -i`
    scp ${hostlist[${i}]}:.ssh/authorized_keys /tmp/$file
    if cat /tmp/$file | grep "`cat mike.pub`"
        then
        echo "Key already exists"
        rm -rf /tmp/$file
    else
        cat mike.pub >> /tmp/$file
        if cat /tmp/$file | grep "`cat mike.pub`"
            then
                echo "Key Successfully Adde"
                scp /tmp/$file ${hostlist[${i}]}:.ssh/authorized_keys
                                rm -rf /tmp/$file
            else
                echo "Failed to add key for host \"${hostlist[${i}]}\" Check manually.\n"
                                echo "Local File \"/tmp/$file\" "
        fi
    fi
done