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.
1. Command Overview
Section titled “1. Command Overview”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.
2. Basic Syntax
Section titled “2. Basic Syntax”- ssh [options] [user@]hostname [command]
- scp [options] [user@]hostname:source_file [user@]hostname:destination_file
- sftp [options] [user@]hostname
3. Practical Examples
Section titled “3. Practical Examples”3.1. Basic SSH Login:
ssh user@remote_hostExample 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])? yesWarning: 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.5user@remote_host:~$3.2. Executing a Command Remotely:
ssh user@remote_host "uptime"Example Output:
10:05:00 up 1 day, 2:05, 1 user, load average: 0.01, 0.02, 0.003.3. Securely Copying a File (SCP):
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:003.4. Secure File Transfer (SFTP):
sftp user@remote_hostExample Output:
Connected to remote_host.sftp> ls -ldrwxr-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 .bashrcsftp> get remote_file.txtFetching /home/user/remote_file.txt to remote_file.txt/home/user/remote_file.txt 100% 10KB 10.0KB/s 00:00sftp> exit3.5. Port Forwarding (Local):
ssh -L local_port:remote_host:remote_port user@gateway_hostExample: Forward port 8080 on your local machine to port 80 on internal_server:
ssh -L 8080:internal_server:80 user@gateway_serverNow, accessing localhost:8080 in your browser will connect to internal_server:80 through the secure SSH tunnel.
3.6. Port Forwarding (Remote):
ssh -R remote_port:local_host:local_port user@gateway_hostExample: Allow connections to your local machine’s port 22 from the remote gateway server on port 5000:
ssh -R 5000:localhost:22 user@gateway_serverNow, 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):
ssh -D local_port user@remote_hostExample: Create a SOCKS proxy on port 1080:
ssh -D 1080 user@remote_hostConfigure your browser or other application to use a SOCKS proxy at localhost:1080 to route traffic through the remote host.
4. Common Options
Section titled “4. Common Options”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.-vis 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).-Yis 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. Advanced Usage
Section titled “5. Advanced Usage”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/nullNow 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.
ssh -A user@remote_host5.3. Using rsync over SSH for Efficient File Synchronization:
rsync is more efficient than scp for syncing directories, as it only transfers changed files.
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
# On local machinessh -L 1234:localhost:5678 user@remote_server "nc -l -p 5678"
# On remote machinenc localhost 1234This example creates a tunnel between the local machine’s port 1234 and the remote server’s port 5678, using netcat for data transfer.
6. Tips & Tricks
Section titled “6. Tips & Tricks”- Use SSH Keys: Avoid password authentication for increased security. Generate a key pair with
ssh-keygen. - Disable Password Authentication: In
/etc/ssh/sshd_configon the server, setPasswordAuthentication noandChallengeResponseAuthentication no. Restart the SSH daemon. - Change the Default SSH Port: Change the default port (22) in
/etc/ssh/sshd_configto a higher, less common port. Restart the SSH daemon. - Use
tmuxorscreen: 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’sauthorized_keysfile: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+Rto 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 usingpsandkill. - Use
grepwithpsto find SSH tunnels:ps aux | grep "ssh -L"to find the SSH processes used for port forwarding.
7. Troubleshooting
Section titled “7. Troubleshooting”- “Permission denied (publickey)”: The server doesn’t have your public key in its
authorized_keysfile. Usessh-copy-idor 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_hostsor usessh-keygen -R hostnameto 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 (
-Xor-Y) and the server (X11Forwarding yesin/etc/ssh/sshd_config). Also, ensure thexauthpackage is installed on the server.
8. Related Commands
Section titled “8. Related Commands”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.