Skip to content

Instantly share code, notes, and snippets.

@aandis
Created July 18, 2016 10:34
Show Gist options
  • Save aandis/143048f875a399d84a7c6fb2256adcd2 to your computer and use it in GitHub Desktop.
Save aandis/143048f875a399d84a7c6fb2256adcd2 to your computer and use it in GitHub Desktop.
Script to automatically setup password less ssh login
#!/bin/bash
usage() { echo "Usage: $0 -L [-U <user_name>] [-H <host>] [-h <hostname>] " 1>&2; exit 1; }
# Input
login=false # Open ssh session after set up, defaults to false.
while getopts "h:U:H:L" opt; do
case $opt in
U) user=$OPTARG ;;
H) host=$OPTARG ;;
h) hostname=$OPTARG ;;
L) login=true ;;
*) usage ;;
esac
done
shift $(($OPTIND - 1))
if [ -z $user ] || [ -z $host ] || [ -z $hostname ]; then
usage
fi
# Input end
echo "Working the magic.."
key_content=`cat .ssh/id_rsa.pub`
ssh $user@$host "mkdir -p .ssh &&
echo $key_content >> .ssh/authorized_keys &&
chmod -R 700 .ssh &&
chmod 640 .ssh/authorized_keys"
code=$?
if [ $code -ne 0 ]; then
echo "Failed. Check your ssh access and permissions."
exit 1
fi
echo -e "Host $hostname\n\t Hostname $host\n\t User $user" >> ~/.ssh/config
echo -e "It worked.\nYou can now ssh to $hostname as $user without a password."
if $login; then
echo "Beginning ssh session."
ssh $user@$host
exit 0
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment