ShadowArch/Shared/replicate-ssh-profiles
2017-03-30 12:44:53 -05:00

59 lines
2.6 KiB
Bash
Executable File

#!/bin/bash
# Process CLI arguments to set up assumptions.
searchterm="$1"
if [ -z "$searchterm" ]; then searchterm="'*'"; fi
### <summary>
### Sets up key-based auth to remote hosts and replicate local .bashrc and .profile to them.
### Assumes that
### </summary>
### <param name="searchterm">(Assumed) term to search for as a prefix</param>
### <param name="system">(Assumed) system .ssh/config hostname</param>
### <param name="realname">(Assumed) system real hostname</param>
function push() {
tput setaf 2; tput bold; printf "$system ($realname) ... \n"; tput sgr0;
# Find the Private key to use.
privfile="$(grep IdentityFile $HOME/.ssh/config | grep `echo $system | cut -f 1 -d '-'` | head -n 1 | cut -f 2 -d ' ')"
if [ -z "$privfile" ]; then privfile="$HOME/.ssh/id_rsa"; fi
command='echo mkdir -p "$HOME/.ssh" &> /dev/null; mkdir -p "$HOME/.ssh"; chmod 0700 $HOME $HOME/.ssh; echo "'`cat $privfile.pub`'" >> $HOME/.ssh/authorized_keys; cp $HOME/.ssh/authorized_keys $HOME/.ssh/id_rsa.pub; chmod 0600 $HOME/.ssh/authorized_keys; chown -R `whoami` $HOME 2>/dev/null; mv $HOME/.profile $HOME/.profile.bak 2>/dev/null; mv $HOME/.bashrc $HOME/.bashrc.bak 2>/dev/null; printf "";'
# Make sure that we have the right host signature.
ssh-keygen -R "$realname"
if [ $? -ne 0 ]; then printf "FAILED\n\n"; return; fi
ssh-keyscan -H "$realname" >> ~/.ssh/known_hosts
if [ $? -ne 0 ]; then printf "FAILED\n\n"; return; fi
# Set up home folder and send public key.
ssh -t $system bash -c "$command"
if [ $? -ne 0 ]; then printf "FAILED\n\n"; return; fi
# Self-allow key-based auth
scp $privfile $system:.ssh/id_rsa
if [ $? -ne 0 ]; then printf "FAILED\n\n"; return; fi
# Pass profiles.
scp $HOME/.bashrc $system:.bashrc
if [ $? -ne 0 ]; then printf "FAILED\n\n"; return; fi
scp $HOME/.profile $system:.profile
if [ $? -ne 0 ]; then
printf "FAILED\n\n";
else
printf "DONE\n\n"
fi
}
### <summary>
### If the search term is in ~/.ssh/config, then replicate to all matching hosts.
### Otherwise, replicate to target specifically.
### </summary>
### <param name="searchterm">(Assumed) term to search for as a prefix</param>
if [ `grep -c "$searchterm" "$HOME/.ssh/config"` -gt 0 ]; then
for system in `egrep '^Host ' $HOME/.ssh/config | cut -f 2 -d ' ' | egrep $searchterm`; do
entry=$(cat -n $HOME/.ssh/config | grep $system | head -n 1 | xargs | cut -f 1 -d ' ')
linenum=$(( $entry + 1 ))
realname="$(cat -n $HOME/.ssh/config | grep " ${linenum}$(printf '\t')" | rev | cut -f 1 -d ' ' | rev)"
if [ -z "$realname" ]; then realname="$system"; fi
push;
done
else
system="$searchterm"
push;
fi