SSH

Commands

  • Generate SSH keys: ssh-keygen -t rsa -b 4096 -C "root@localhost"

Two key files will be created directory .ssh directory. The file id_rsa.pub is the public key file, and id_rsa is your private key file.

  • Copy the public key on a remote machine: ssh-copy-id root@<hostname> or ssh-copy-id -i /root/.ssh/id_rsa.pub <hostname>
  • Copy the public key manually on a remote machine (just the first time): cat /root/.ssh/id_rsa.pub | ssh root@<hostname> 'mkdir -m 700 /root/.ssh; cat >> /root/.ssh/authorized_keys; chmod 600 /root/.ssh/authorized_keys'
  • Add a public key on a remote machine: cat /root/.ssh/id_rsa.pub | ssh root@<hostname> 'cat >> /root/.ssh/authorized_keys'
  • Create the public key on a remote machine:
su - <user>

mkdir .ssh

vi .ssh/authorized_keys ==> paste the public key here

chmod 700 .ssh
chmod 600 .ssh/authorized_keys
  • Start the authentication agent: evalssh-agent``
  • Add the private key identities to the authentication agent: ssh-add
  • Lists fingerprints of all identities currently represented by the agent: ssh-add -l
  • Lists public key parameters of all identities currently represented by the agent: ssh-add -L
  • Remove identities from the agent: ssh-add -d /root/.ssh/id_rsa
  • Delete all identities from the agent: ssh-add -D
  • Set a maximum lifetime when adding identities to an agent: ssh-add -t 3600
  • Search for the specified hostname in a known_hosts file: ssh-keygen -F <hostname>
  • Removes all keys belonging to hostname from a known_hosts file: ssh-keygen -R <hostname>

Recipes

Forward the private SSH key to a different server
  1. Edit SSH client configuration file

vi /.ssh/config

Host *
ForwardAgent yes
  1. Start SSH agent even if the private key is not protected by a passphrase
eval `ssh-agent`
  1. Add RSA or DSA identities to the authentication agent

ssh-add

  1. Enables forwarding of the authentication agent connection. Now the private is forwarded on the server and from here you can connect to what server you want

ssh -A <hostname>

Compare two files

ssh <remote-host> "cat /path/to/remotefile" | diff - /path/to/localfile

Control Master

vi ~/.ssh/config

Host *
ControlMaster auto
ControlPath ~/.ssh/master-%r@%h:%p
  • Host * – all hosts
  • ControlPath ~/.ssh/master-%r@%h:%p – Path for creating the control file, make sure that this file is not accessible by others.

%r – remote login name %h – host name ( remote ) %p – port

Links