Saturday, April 1, 2017

Accessing Github Through SSH As Different Users

To set up access to Github using different accounts, start by creating ssh keys for each account.

$ cd ~/.ssh
$ ssh-keygen -t rsa -C "github-acct1" -f "github-acct1"
Then add the ssh key to the Github account.

Next, create ~/.ssh/config to tell ssh when to use which account (set permission to be 600):

# Github account #1                                              
Host github.com-acct1                                                                 
   HostName github.com                                                          
   User git                                                                     
   IdentityFile ~/.ssh/github-acct1                                           
                                                                                
# Github account #2                                                         
Host github.com-acct2                                                        
   HostName github.com                                                          
   User git                                                                     
   IdentityFile ~/.ssh/github-acct2

Check out a repo as the user to use by matching to the Host value in ~/.ssh/config:

$ git clone git@github.com-acct1:repo
Change to the repo directory and set the name and email to use for commits if needed.

$ cd repo
$ git config user.name "Acct1"
$ git config user.email acct1@example.com

To avoid accidentally using the wrong account (e.g. default):

$ git config --global --unset user.name
$ git config --global --unset user.email
$ git config --global user.useConfigOnly true
If you get an error message about the user (or the wrong user) not having the right permission to access the repo:

$ eval "$(ssh-agent -s)"
$ ssh-add