Skip to content

SSH and Remote Access

Category: Intermediate Linux Commands
Type: Linux Commands
Generated on: 2025-07-10 03:10:59
For: System Administration, Development & Technical Interviews


SSH and Remote Access - Linux Cheatsheet (Intermediate)

Section titled “SSH and Remote Access - Linux Cheatsheet (Intermediate)”

This cheatsheet covers SSH and related commands for secure remote access, targeting both system administrators and developers.

Purpose: SSH (Secure Shell) allows you to securely access and manage remote systems over a network. It encrypts all traffic, preventing eavesdropping and data manipulation. This cheatsheet also covers related tools for secure file transfer and port forwarding.

When to Use:

  • Remotely logging into servers to manage them.
  • Executing commands on remote machines.
  • Securely transferring files between systems.
  • Creating secure tunnels for network services.
  • ssh [options] [user@]hostname [command]
  • scp [options] [user@]hostname:source_file [user@]hostname:destination_file
  • sftp [options] [user@]hostname

3.1. Basic SSH Login:

Terminal window
ssh user@remote_host

Example Output:

The authenticity of host 'remote_host (192.168.1.10)' can't be established.
ECDSA key fingerprint is SHA256:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'remote_host,192.168.1.10' (ECDSA) to the list of known hosts.
user@remote_host's password:
Welcome to Ubuntu 20.04.3 LTS (GNU/Linux 5.4.0-122-generic)
* Documentation: https://help.ubuntu.com
Last login: Tue Oct 25 10:00:00 2023 from 192.168.1.5
user@remote_host:~$

3.2. Executing a Command Remotely:

Terminal window
ssh user@remote_host "uptime"

Example Output:

10:05:00 up 1 day, 2:05, 1 user, load average: 0.01, 0.02, 0.00

3.3. Securely Copying a File (SCP):

Terminal window
scp local_file.txt user@remote_host:/path/to/destination/

Example Output (verbose mode):

scp -v local_file.txt user@remote_host:/path/to/destination/
Executing: program /usr/bin/ssh -x -oForwardAgent=no -oPermitLocalCommand=no -oClearAllForwardings=yes -oBatchMode=yes -oConnectTimeout=10 -oKexAlgorithms=+diffie-hellman-group14-sha1 -s scp -v -t /path/to/destination/
... (lots of debug output) ...
local_file.txt 100% 10KB 10.0KB/s 00:00

3.4. Secure File Transfer (SFTP):

Terminal window
sftp user@remote_host

Example Output:

Connected to remote_host.
sftp> ls -l
drwxr-xr-x 2 user user 4096 Oct 25 10:00 .
drwxr-xr-x 3 root root 4096 Oct 25 09:00 ..
-rw------- 1 user user 0 Oct 25 09:00 .bash_history
-rw-r--r-- 1 user user 220 Oct 25 09:00 .bash_logout
-rw-r--r-- 1 user user 3771 Oct 25 09:00 .bashrc
sftp> get remote_file.txt
Fetching /home/user/remote_file.txt to remote_file.txt
/home/user/remote_file.txt 100% 10KB 10.0KB/s 00:00
sftp> exit

3.5. Port Forwarding (Local):

Terminal window
ssh -L local_port:remote_host:remote_port user@gateway_host

Example: Forward port 8080 on your local machine to port 80 on internal_server:

Terminal window
ssh -L 8080:internal_server:80 user@gateway_server

Now, accessing localhost:8080 in your browser will connect to internal_server:80 through the secure SSH tunnel.

3.6. Port Forwarding (Remote):

Terminal window
ssh -R remote_port:local_host:local_port user@gateway_host

Example: Allow connections to your local machine’s port 22 from the remote gateway server on port 5000:

Terminal window
ssh -R 5000:localhost:22 user@gateway_server

Now, someone on gateway_server can SSH into your local machine by SSHing to localhost:5000 on gateway_server.

3.7. Dynamic Port Forwarding (SOCKS Proxy):

Terminal window
ssh -D local_port user@remote_host

Example: Create a SOCKS proxy on port 1080:

Terminal window
ssh -D 1080 user@remote_host

Configure your browser or other application to use a SOCKS proxy at localhost:1080 to route traffic through the remote host.

SSH:

  • -p port: Specify a non-standard port. Example: ssh -p 2222 user@remote_host
  • -i identity_file: Use a specific private key file for authentication. Example: ssh -i ~/.ssh/my_private_key user@remote_host
  • -v, -vv, -vvv: Increase verbosity for debugging. -v is usually sufficient.
  • -N: Do not execute a remote command. Useful for port forwarding. Example: ssh -N -L 8080:localhost:80 user@remote_host
  • -f: Background the SSH session after authentication. Often used with -N. Example: ssh -f -N -L 8080:localhost:80 user@remote_host
  • -T: Disable pseudo-terminal allocation. Useful for scripts.
  • -X, -Y: Enable X11 forwarding (run graphical applications remotely). -Y is less secure but allows untrusted X11 clients.
  • -C: Enable compression. Can improve performance on slow networks.
  • -o option=value: Specify SSH configuration options directly. Example: ssh -o StrictHostKeyChecking=no user@remote_host
  • -q: Quiet mode. Suppresses most warning and diagnostic messages.

SCP:

  • -P port: Specify a non-standard port. Example: scp -P 2222 local_file.txt user@remote_host:/path/to/destination/
  • -r: Recursively copy directories. Example: scp -r local_directory user@remote_host:/path/to/destination/
  • -v: Verbose mode for debugging.
  • -C: Enable compression.
  • -q: Quiet mode.

SFTP:

  • -P port: Specify a non-standard port. Example: sftp -P 2222 user@remote_host
  • -v: Verbose mode for debugging.
  • -b batchfile: Execute commands from a batch file. Example: sftp -b sftp_commands.txt user@remote_host

5.1. SSH Configuration File (~/.ssh/config):

Create or edit ~/.ssh/config to define settings for specific hosts. This eliminates the need to repeatedly type options.

Host my_server
HostName remote_host.example.com
User my_user
Port 2222
IdentityFile ~/.ssh/my_private_key
StrictHostKeyChecking no
UserKnownHostsFile /dev/null

Now you can simply use: ssh my_server

5.2. SSH Agent Forwarding:

Forward your SSH agent to the remote server, allowing you to use your local SSH keys to authenticate to other servers from the remote server. Use with caution, as it can compromise security.

Terminal window
ssh -A user@remote_host

5.3. Using rsync over SSH for Efficient File Synchronization:

rsync is more efficient than scp for syncing directories, as it only transfers changed files.

Terminal window
rsync -avz -e "ssh -p 2222" local_directory user@remote_host:/path/to/destination/

Explanation:

  • -a: Archive mode (preserves permissions, timestamps, etc.)
  • -v: Verbose mode.
  • -z: Enable compression.
  • -e "ssh -p 2222": Specify the SSH command to use (including the port if needed).

5.4. Multiplexing SSH Connections:

Reduce connection overhead by reusing an existing SSH connection for multiple sessions. Add these lines to your ~/.ssh/config:

Host *
ControlMaster auto
ControlPath ~/.ssh/sockets/%r@%h:%p
ControlPersist 600 # Keep the master connection open for 10 minutes (600 seconds)

The first time you connect to a server, a master connection is established. Subsequent connections to the same server will reuse this connection, making them much faster.

5.5. Tunneling with Netcat via SSH

Terminal window
# On local machine
ssh -L 1234:localhost:5678 user@remote_server "nc -l -p 5678"
# On remote machine
nc localhost 1234

This example creates a tunnel between the local machine’s port 1234 and the remote server’s port 5678, using netcat for data transfer.

  • Use SSH Keys: Avoid password authentication for increased security. Generate a key pair with ssh-keygen.
  • Disable Password Authentication: In /etc/ssh/sshd_config on the server, set PasswordAuthentication no and ChallengeResponseAuthentication no. Restart the SSH daemon.
  • Change the Default SSH Port: Change the default port (22) in /etc/ssh/sshd_config to a higher, less common port. Restart the SSH daemon.
  • Use tmux or screen: Maintain persistent sessions on the remote server, even if your SSH connection drops.
  • ssh-copy-id: Easily copy your public key to a remote server’s authorized_keys file: ssh-copy-id user@remote_host
  • Tab Completion: Use tab completion for filenames, hostnames, and usernames in SSH, SCP, and SFTP.
  • History Search: Use Ctrl+R to search your command history for previously used SSH commands.
  • Background SSH Connections: Use ssh -f -N ... to start a port forwarding tunnel in the background. You can later terminate it using ps and kill.
  • Use grep with ps to find SSH tunnels: ps aux | grep "ssh -L" to find the SSH processes used for port forwarding.
  • “Permission denied (publickey)”: The server doesn’t have your public key in its authorized_keys file. Use ssh-copy-id or manually add the key.
  • “Connection refused”: The SSH daemon is not running on the remote host, or a firewall is blocking the connection. Check the SSH service status (systemctl status sshd) and firewall rules.
  • “Host key verification failed”: The host key has changed. Remove the old key from ~/.ssh/known_hosts or use ssh-keygen -R hostname to remove the entry. Alternatively, use -o StrictHostKeyChecking=no (but understand the security implications).
  • Slow SSH connection: Check network connectivity, DNS resolution, and try enabling compression (-C).
  • X11 forwarding not working: Ensure X11 forwarding is enabled on both the client (-X or -Y) and the server (X11Forwarding yes in /etc/ssh/sshd_config). Also, ensure the xauth package is installed on the server.
  • ssh-keygen: Generate SSH key pairs.
  • ssh-agent: Manage SSH keys in memory.
  • ssh-add: Add SSH keys to the SSH agent.
  • scp: Securely copy files.
  • sftp: Secure file transfer program.
  • rsync: Remote file synchronization.
  • netcat (nc): A utility for reading from and writing to network connections (used in tunneling).
  • tmux / screen: Terminal multiplexers for persistent sessions.
  • firewall-cmd / ufw: Firewall management tools.
  • systemctl: Manage system services, including SSH.

This cheatsheet provides a comprehensive overview of SSH and related commands. Remember to consult the man pages (man ssh, man scp, man sftp) for complete documentation. Always prioritize security best practices when configuring and using SSH.