Skip to content

Instantly share code, notes, and snippets.

@alvaromuir
Last active August 29, 2015 14:12
Show Gist options
  • Save alvaromuir/4525a2c190c7c49c31a8 to your computer and use it in GitHub Desktop.
Save alvaromuir/4525a2c190c7c49c31a8 to your computer and use it in GitHub Desktop.
BASH script that automates paswordless ssh.
#!/bin/bash
# Script to create passwordless ssh on remote machine from current host
# requires ssh, naturally
# example usage: ssh-auth foreign.host.com id_dsa.pub myUserName
# @alvaromuir, 6.19.15
set -e
USAGECMD="Usage: $0 <hostname> <public-key.pub> [opt: username]"
SSHHOME=~/.ssh/
if [ "$3" ]
then
USER="$3"
else
USER=`whoami`
fi
CONNMSG="connecting to $1 using $2 as $USER"
if [ -z "$1" ]
then
echo "ERROR - No hostname supplied." $USAGECMD
exit
else
if [ `builtin type -p cat` ]
then
CATCMD=`which cat`
# echo $CATCMD
if [ `builtin type -p ssh` ]
then
SSHCMD=`which ssh`
if [ -z "$2" ]
then
keys=()
for i in $SSHHOME*.pub
do
keys+=("$i")
done
if [ ${#keys[@]} > 1 ]
then
echo ''
echo "${#keys[@]} Keys found in $SSHHOME:"
printf -- '%s\n' "${keys[@]/"$SSHHOME"}"
echo ''
echo $USAGECMD
else
echo $CONNMSG
fi
else
if [ ! -e $SSHHOME$2 ]
then
echo "ERROR: $SSHHOME$2 not found"
else
echo $CONNMSG
$CATCMD $SSHHOME$2 | $SSHCMD $USER@$1 "mkdir -p ~/.ssh && chmod 700 .ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
fi
fi
else echo "ERROR - No openssh executable found in \$PATH";
fi
else
echo "ERROR - No \`cat\` executable found in \$PATH";
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment