Skip to content

Instantly share code, notes, and snippets.

@domguard
Created June 27, 2012 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save domguard/3002507 to your computer and use it in GitHub Desktop.
Save domguard/3002507 to your computer and use it in GitHub Desktop.
Install SSH Keys
#!/bin/sh
USER="${1}"
HOST="${2}"
ALIAS="${3}"
if [ ! "${USER}" ] && [ ! "${HOST}" ] && [ ! "${ALIAS}" ]; then
echo
echo "Usage: installSSHKey username hostname alias"
echo
echo " username = Your username on the remote system (not necessarily your current username: `whoami`)"
echo " hostname = The hostname (domain name or IP address) of the remote server"
echo " alias = The ssh alias for this host to be created"
echo
fi
if [ ! "${USER}" ]; then
echo "No ssh username specified (EG: `whoami`)"
exit 1
fi
if [ ! "${HOST}" ]; then
echo "No hostname specified (EG: www.example.com)"
exit 1
fi
if [ ! "${ALIAS}" ]; then
echo "No ssh alias specified (EG: example)"
exit 1
fi
echo "Public keys will be generated and installed on the ssh"
echo "host ${USER}@${HOST} identified by the key ${ALIAS}."
echo -n "If this is correct, type yes: "
read YESNO
if [ ! "${YESNO}" == "yes" ]; then
exit 0
fi
cd ~
if [ ! -r .ssh ]; then
echo -n "Creating hidden .ssh folder in home directory..."
mkdir -p .ssh
chmod 700 .ssh
echo "Done"
fi
if [ ! -r .ssh/config ]; then
echo -n "Creating host configuration file..."
echo "StrictHostKeyChecking=no
CheckHostIP=no" > .ssh/config
chmod 600 .ssh/config
echo "Done"
fi
echo -n "Adding host to config file..."
echo "
Host ${ALIAS}
HostKeyAlias ${ALIAS}
Hostname "${HOST}"
User ${USER}
Compression yes" >> .ssh/config
echo "Done"
if [ ! -r .ssh/id_rsa.pub ]; then
echo -n "Creating RSA private and public keys..."
ssh-keygen -q -t rsa -f .ssh/id_rsa -N "" -P ""
chmod 600 .ssh/id_rsa*
echo "Done"
fi
if [ ! -r .ssh/id_dsa.pub ]; then
echo -n "Creating DSA private and public keys..."
ssh-keygen -q -t dsa -f .ssh/id_dsa -N "" -P ""
chmod 600 .ssh/id_dsa*
echo "Done"
fi
echo "Installing SSH public keys onto server: ${HOST}..."
echo "You will be prompted for your remote password."
ssh "${ALIAS}" \
mkdir -p .ssh\; \
echo "`cat .ssh/id_rsa.pub`" \>\> .ssh/authorized_keys\; \
echo "`cat .ssh/id_dsa.pub`" \>\> .ssh/authorized_keys2\; \
chmod 700 .ssh\; \
chmod 600 .ssh/*\;
if [ ! $? == 0 ]; then
echo "An error occurred, please overview your output"
else
echo "Done"
echo
echo "You can now access the server ${HOST} by typing:"
echo
echo " ssh ${ALIAS}"
echo
echo "Commands can be performed without logging in by doing:"
echo
echo " ssh ${ALIAS} commandname"
echo
echo "Examples:"
echo " ssh ${ALIAS} whoami"
echo " ssh ${ALIAS} ps ax"
echo " ssh ${ALIAS} tail -f /var/log/system.log"
echo
fi
chmod 600 .ssh/*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment