Skip to content

Instantly share code, notes, and snippets.

@juanique
Last active November 2, 2024 05:49
Show Gist options
  • Select an option

  • Save juanique/4092969 to your computer and use it in GitHub Desktop.

Select an option

Save juanique/4092969 to your computer and use it in GitHub Desktop.
Bash script to add a new SSH key to your GitHub account
rm -rf ~/.ssh/id_rsa ~/.ssh/id_rsa.pub
read -p "Enter github email : " email
echo "Using email $email"
ssh-keygen -t rsa -b 4096 -C "$email"
ssh-add ~/.ssh/id_rsa
pub=`cat ~/.ssh/id_rsa.pub`
read -p "Enter github username: " githubuser
echo "Using username $githubuser"
read -s -p "Enter github password for user $githubuser: " githubpass
curl -u "$githubuser:$githubpass" -X POST -d "{\"title\":\"`hostname`\",\"key\":\"$pub\"}" https://api.github.com/user/keys
@cdaringe
Copy link

cdaringe commented Nov 9, 2019

i found the rm -rf a bit aggressive, wanted to use existing keys if present, and further support two-factor-auth. here's my flavor! thx for the boilerplate :)

function git_upload_ssh_key () {
  read -p "Enter github email : " email
  echo "Using email $email"
  if [ ! -f ~/.ssh/id_rsa ]; then
    ssh-keygen -t rsa -b 4096 -C "$email"
    ssh-add ~/.ssh/id_rsa
  fi
  pub=`cat ~/.ssh/id_rsa.pub`
  read -p "Enter github username: " githubuser
  echo "Using username $githubuser"
  read -s -p "Enter github password for user $githubuser: " githubpass
  echo
  read -p "Enter github OTP: " otp
  echo "Using otp $otp"
  echo
  confirm
  curl -u "$githubuser:$githubpass" -X POST -d "{\"title\":\"`hostname`\",\"key\":\"$pub\"}" --header "x-github-otp: $otp" https://api.github.com/user/keys
}

@juanique
Copy link
Author

Is there a way to check if the user uses two-factor auth and only ask for it if they do? ideally the script should cover both cases. If you can take care of that part I'll update the gist to your version which looks much better :)

@morganrivers
Copy link

I made a little script that also does this but allows you to keep several names at once, it also contains some more explanation and walkthrough on the page. Hopefully this is useful to someone, as I found this process quite opaque when I first had to do it for my private repositories:

https://github.com/morganrivers/how_to_ssh_key

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment