Skip to content

OpenSSH cheatsheet

Basics

Connect to the remote server

ssh user@server

or

ssh -l user server

Connect to the server on different port

ssh -p 2222 user@server

Connect with the private key

ssh -i ~/path/to/key/file user@server

Connect via multiple jumps

ssh -J user@jump1,user@jump2 user@server

Usage of ProxyCommand

ssh -o ProxyCommand="ssh -W %h:%p user@jump" user@server

Options used:

  • -W - Requests that standard input and iutput on the client are forwarded to host on port
  • %h - Host to connect to
  • %p - Port to connect to on remote host

Local Port Forwarding

Local port forwarding

ssh -L 8000:host:80 user@server

Points local port 8000 to port 80 on server.

Local port forwarding via server

ssh -L laddr:lport:raddr:rport user@server

Remote Port Forwarding

Forward remote port (-R) 9000 to local port 80:

ssh -R 9000:localhost:80 user@server

To allow remote host to listen on the interface, change sshd configuration on remote host (/etc/ssh/sshd_config):

GatewayPorts yes

Socks proxy

ssh -D 1080 login@server

Socks proxy via multiple jumps

ssh -J user@jump1 user2@jump2 -D 1080

Connection keep-alive

Specify keep-alive interval of 60 seconds in command-line

ssh -o ServerAliveInterval=60 user@server

Set interval in .ssh/config for all hosts

Host *
  ServerAliveInterval 60

Pseudo terminal

Force pseudo-terminal

Force SSH to set pseudo-terminal

ssh -t user@server

Force pseudo-terminal and execute command

ssh -t user@server 'screen'

Environment variables

Set environment variable in SSH session

export VARIABLE_NAME=test
ssh user@server -o SendEnv=VARIABLE_NAME

Generating keys

Generate new key-pair

ssh-keygen

Use different algorithm

ssh-keygen -t rsa -b 4096
ssh-keygen -t dsa 
ssh-keygen -t ecdsa -b 521
ssh-keygen -t ed25519

Specify the file name

ssh-keygen -f ~/your-key

Copy SSH key to the server

Install SSH key on the server

ssh-copy-id -i ~/path/to/key user@server

SCP

Copy file to the server

scp /path/to/file user@server:destination/path

Copy file from the server

scp user@server:path/to/file destination/path

Recursively copy

scp -r /path/to/file user@server:destination/path

Specify port to connect to

scp -P 2222 /path/to/file user@server:destination/path