Skip to content

Instantly share code, notes, and snippets.

@rbf
Last active December 20, 2015 09:58
Show Gist options
  • Save rbf/6111562 to your computer and use it in GitHub Desktop.
Save rbf/6111562 to your computer and use it in GitHub Desktop.
One-liner to obtain the public ssh key, creating it in the way if not present.

Description

One-liner to obtain the public ssh key, creating it in the way if not present. Based on https://help.github.com/articles/generating-ssh-keys.

Execution

To directly execute the command in a shell, type:

eval $(curl -sSL https://gist.github.com/rbf/6111562/raw/sshkey)

This will create an SSH key if it is not already present at ~/.ssh/id_rsa.pub, asking for your email to be used as label for the new SSH key. If a SSH key is already present, this step will not be executed. In any case, once a ~/.ssh/id_rsa.pub file exists, the command to add the new public key into another machine's ~/.ssh/authorized_keys file will be printed (not executed). You will see something like this at the end:

Type following command on the machines where you want to grant access to:

cat << EOF >> ~/.ssh/authorized_keys
ssh-rsa BAAAB3NzaC1yc2EAACADAQABAAABAQDXaNhCDeNAIuaasdV5QYesvx6Aasd0f9asdf0a9f9nfd8v434gBsVn/74lMwNweKP3vHCLSXu8BEf4ScPveCDpXzLqSZxduylwNQe6A6WPDMultYI6frzzmTLY0rYohtRG09i4309fimfdsofnwWq1ZNM/s5WM57w/N1cfsp+/0iqD1TvVppVlu8s7bVXxWh0TxByrkGxvuFsFRo4cX2j0Kn0cwIBaW+ySe3QIyn1ZC4Rus9j+6fxgeg1AAUc2Y+SJ5vg7n4GiqpBTmgMjabm2tHZRCBwGJkkBpeta9834fdshMoFxyFCk4Ff2xSsbC/ZHnca56NSO8abheOz0umT label@example.com
EOF

Now you can easily copy&paste it in the machines where you want to grant access to.

Sometimes GitHub might take a bit long to answer and respones with a 502 Bad Gateway code and an HTML with the message "OH NO! This page is taking way too long to load. Sorry about that. Please try refreshing and contact us if the problem persists." In that case, your shell won't be able to process the code and the result of the command above will look something like: -bash: syntax error near unexpected token '<'. In that case, just try it again until it works (usually next time is already ok).

To simply print the command in a shell, use:

curl -sSL https://gist.github.com/rbf/6111562/raw/sshkey
( [ -e ~/.ssh/id_rsa.pub ] || ssh-keygen -t rsa -C "$(read -p "Your email (as label for the new ssh key): " SSH_EMAIL_LABEL && echo "${SSH_EMAIL_LABEL}")" ) && echo -e "\nType following command on the machines where you want to grant access to:\n\ncat << EOF >> ~/.ssh/authorized_keys\n$(cat ~/.ssh/id_rsa.pub)\nEOF\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment