SSH cheatsheet
The useful SSH
things I forget.
Connection
Start remote shell on host
as user
, assumes port
22, will prompt for password if required:
ssh user@host
Supply non-standard port
:
ssh user@host -p port
Configure connection settings per host in ~/.ssh/config
:
Host hostname1
HostName 192.168.1.1
User other
Port 1234
Host hostname2
PubkeyAuthentication yes
IdentityFile ~/.ssh/id_other
Then connect using stored settings:
ssh hostname1
ssh hostname2
Keys
Assuming you have generated a public-private key-pair locally, id_rsa
and id_rsa.pub
respectively, add your public key to the remote then connect using:
cat id_rsa.pub | ssh user@host 'cat >> .ssh/authorized_keys'
ssh user@host
Find the fingerprint of a public key using:
ssh-keygen -l -f id_rsa.pub
Commands
Run a command on the remote host (and get the stdin and stderr locally):
ssh user@host "ls"
Multiple configurations for a host
Configure fake host names in ~/.ssh/config
to allow multiple credentials for same host:
Host fake1.host
HostName host
User user1
Host fake2.host
HostName host
User user2
Then connect using stored settings:
ssh fake1.host
ssh fake2.host
Use case: Github
Normally, if you want to interact with a remote git repo you might register your own key-pair then connect using something like git@github.com:user/repo1.git
. However, if you need to automate access to different Github repositories you should use different key-pairs for each repo but since you're not specifying the key-pair on the git url, how can you do that? You can configure different key-pairs against fake hostnames for each repo.
Host repo1.github.com
HostName github.com
User git
IdentityFile ~/.ssh/repo1_rsa
Host repo2.github.com
HostName github.com
User git
IdentityFile ~/.ssh/repo2_rsa
Then we can interact with the remotes via those fake host entries, repo1.github.com:user/repo1.git
and repo2.github.com:user/repo1.git
, and the SSH config will ensure that we connect using the appropriate key-pair.