ssh, ssh-agent and scp

Updated at 2017-01-09 02:23

This note is about SSH related commands on Unix machines.

ssh command is an OpenSSH SSH client, a remote login program.

# logging in using details in `~/.ssh/config` or the current user

# logging in as a specific user

# logging in using a specific identity file
ssh -i ~/.ssh/id_home_to_workwork

You can use ssh to execute commands on the remote host.

# run the uptime command on remote host
ssh "uptime"

# execute commands on target host and return the results to the local machine
ssh "mysqldump | gzip" > production.sql.gz

You can use ssh to tunnel connections.

# localhost:8080 -> ->
ssh -L

You should configure ssh so you don't have to write all of those parameters.

# ~/.ssh/config
    IdentityFile ~/.ssh/id_laptop_to_workwork
    IdentityFile ~/.ssh/id_laptop_to_github
Host home
    Port 6000
    User ruksi
    IdentityFile ~/.ssh/id_laptop_to_home

You can establish a SSH tunnel.

# ~/.ssh/config
Host database_tunnel
    IdentityFile ~/.ssh/id_all_to_databasehost_com
    LocalForward 9906
    User ruksi

# Usage:
# -f = Requests ssh to go to background just before command execution.
# -N = Do not execute a remote command.
# ssh -f -N database_tunnel


ssh-agent is a program that holds private keys used for public key auth.

The program is usually started in the beginning of a login session.

ps -ax | grep [s]sh-agent


ssh-keygen generates and converts authentication keys for SSH.

# ~/.ssh should contain all your SSH configurations and identities
cd ~/.ssh
ssh-keygen -t rsa -b 4096 -C ""

Computers have a ~/.ssh/authorized_keys file per user that contains a list of public SSH keys that allow access to that specific user.

You should name your identity files uniformly. E.g. I use id_<ORGANIZATION>_<SERVICE/DESTINATION>.



If a command keeps requesting for SSH key password, you can add it to the authentication agent.

git clone
# => Enter passphrase for key...

ssh-add ~/.ssh/keyname
# input the password once and be done with it until reboot
git clone
# works without a password

ssh-add -l  # lists fingerprints of all identities in the agent
ssh-add -L  # lists public key of all identities in the agent
ssh-add -d  # remove a specific identity from the agent
ssh-add -D  # remove all identities from the agent


You can use secure copy scp to copy files from a computer to another. scp comes with SSH.

scp /file/to/copy.txt  /destination/path

# Copy local archives to remote server.
scp *.tar.gz

# Copy from remote to local.
scp .

# Copy from remote to local while using specified identity file.
scp -i ~/.ssh/id_source_to_destionation ~/