Skip to content

SSH Remote Connection

What is SSH?

SSH (Secure Shell) is an encrypted network protocol for securely logging in and executing commands on unsecure networks. SSH replaces unsecure protocols like telnet, rlogin, etc.

SSH Basics

Installing SSH

bash
# Install SSH client (usually pre-installed)
$ sudo apt install openssh-client

# Install SSH server
$ sudo apt install openssh-server

# Start SSH service
$ sudo systemctl start ssh
$ sudo systemctl enable ssh

# Check status
$ sudo systemctl status ssh

Basic Connection

bash
# Basic format
$ ssh username@hostname

# Connect to remote server
$ ssh maxwell@192.168.1.100
$ ssh maxwell@server.example.com

# Specify port
$ ssh -p 2222 maxwell@192.168.1.100

# Use current username
$ ssh 192.168.1.100

First Connection

First connection will show host fingerprint confirmation:

bash
$ ssh maxwell@192.168.1.100
The authenticity of host '192.168.1.100 (192.168.1.100)' can't be established.
ED25519 key fingerprint is SHA256:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.1.100' (ED25519) to list of known hosts.

SSH Key Authentication

Key authentication is more secure and convenient than password authentication.

Generating Key Pair

bash
# Generate Ed25519 key (recommended)
$ ssh-keygen -t ed25519 -C "your_email@example.com"
Generating public/private ed25519 key pair.
Enter file in which to save key (/home/maxwell/.ssh/id_ed25519):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/maxwell/.ssh/id_ed25519
Your public key has been saved in /home/maxwell/.ssh/id_ed25519.pub

# Generate RSA key (better compatibility)
$ ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

# Specify filename
$ ssh-keygen -t ed25519 -f ~/.ssh/mykey -C "comment"

Key Files

FileDescription
~/.ssh/id_ed25519Private key (keep secret!)
~/.ssh/id_ed25519.pubPublic key (can be distributed)
~/.ssh/authorized_keysAuthorized public key list
~/.ssh/known_hostsKnown host fingerprints
~/.ssh/configClient configuration

Copy Public Key to Server

bash
# Use ssh-copy-id (recommended)
$ ssh-copy-id maxwell@192.168.1.100
$ ssh-copy-id -i ~/.ssh/mykey.pub maxwell@192.168.1.100

# Manual copy
$ cat ~/.ssh/id_ed25519.pub | ssh maxwell@192.168.1.100 \
    "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

# View public key
$ cat ~/.ssh/id_ed25519.pub

Setting Correct Permissions

bash
# Local
$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/id_ed25519
$ chmod 644 ~/.ssh/id_ed25519.pub
$ chmod 600 ~/.ssh/config
$ chmod 700 ~/.ssh
$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/authorized_keys

# Server
$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/authorized_keys

Using Specific Key

bash
$ ssh -i ~/.ssh/mykey maxwell@192.168.1.100

SSH Configuration Files

Client Configuration ~/.ssh/config

bash
# Default configuration
Host *
    ServerAliveInterval 60
    ServerAliveCountMax=3

# Specific host configuration
Host myserver
    HostName 192.168.1.100
    User maxwell
    Port 22
    IdentityFile ~/.ssh/id_ed25519

# Another server
Host dev
    HostName dev.example.com
    User deploy
    Port 2222
    IdentityFile ~/.ssh/deploy_key

# Through jump server
Host internal
    HostName 10.0.0.100
    User admin
    ProxyJump bastion

# Jump server
Host bastion
    HostName bastion.example.com
    User jump

Using configuration after connection:

bash
$ ssh myserver    # Equivalent to ssh maxwell@192.168.1.100
$ ssh dev         # Equivalent to ssh -p 2222 deploy@dev.example.com

Server Configuration /etc/ssh/sshd_config

bash
# Port
Port 22

# Listen address
ListenAddress 0.0.0.0

# Prohibit root login
PermitRootLogin no

# Prohibit password authentication (key-only)
PasswordAuthentication no

# Allow public key authentication
PubkeyAuthentication yes

# Authorized keys file
AuthorizedKeysFile .ssh/authorized_keys

# Maximum authentication attempts
MaxAuthTries3

# Idle timeout
ClientAliveInterval 300
ClientAliveCountMax2

# Limit users
AllowUsers maxwell alice
DenyUsers bob

# Limit groups
AllowGroups sshusers

After modifying configuration, restart SSH:

bash
$ sudo systemctl restart ssh

SSH Advanced Usage

Execute Remote Commands

bash
# Execute single command
$ ssh maxwell@server "ls -la"

# Execute multiple commands
$ ssh maxwell@server "cd /var/www && git pull"

# Interactive commands need -t
$ ssh -t maxwell@server "sudo apt update"

Port Forwarding

Local Port Forwarding

Forward local port to remote host:

bash
# Format: ssh -L local_port:target_host:target_port jump_host
$ ssh -L 8080:localhost:80 maxwell@server
# Then connect locally to localhost:8080

# Access remote database
$ ssh -L 3306:localhost:3306 maxwell@server
# Then locally connect to localhost:3306

# Access internal network via jump server
$ ssh -L 8080:internal.server:80 maxwell@bastion

Remote Port Forwarding

Forward remote port to local:

bash
# Format: ssh -R remote_port:local_host:local_port server
$ ssh -R 8080:localhost:3000 maxwell@server
# Remote access server:8080 will forward to local 3000

Dynamic Port Forwarding (SOCKS Proxy)

bash
$ ssh -D 1080 maxwell@server
# Local 1080 port becomes SOCKS5 proxy

Background Running Port Forward

bash
# -f Background run, -N no command
$ ssh -fN -L 8080:localhost:80 maxwell@server

File Transfer

scp - Secure Copy

bash
# Upload file to server
$ scp file.txt maxwell@server:/home/maxwell/

# Upload to specified path
$ scp file.txt maxwell@server:~/

# Upload to specific path
$ scp file.txt maxwell@server:/var/www/

# Download from server
$ scp maxwell@server:/var/log/app.log ./

# Copy directory
$ scp -r directory/ maxwell@server:~/

# Specify port
$ scp -P 2222 file.txt maxwell@server:~

# Use configuration file's host
$ scp file.txt myserver:~/

rsync - Efficient Sync

bash
# Sync directory to server
$ rsync -avz ./local/ maxwell@server:/remote/

# Sync from server
$ rsync -avz maxwell@server:/remote/ ./local/

# Delete target's non-existent files
$ rsync -avz --delete ./local/ maxwell@server:/remote/

# Exclude files
$ rsync -avz --exclude='*.log' ./local/ maxwell@server:/remote/

# Show progress
$ rsync -avz --progress ./local/ maxwell@server:/remote/

# Dry run (not actually execute)
$ rsync -avzn ./local/ maxwell@server:/remote/

sftp - Interactive Transfer

bash
$ sftp maxwell@server
sftp> ls
sftp> cd /var/www
sftp> put local_file.txt
sftp> get remote_file.txt
sftp> mkdir new_dir
sftp> rm old_file.txt
sftp> quit

SSH Agent

SSH Agent can cache private key passwords:

bash
# Start agent
$ eval $(ssh-agent)

# Add key
$ ssh-add ~/.ssh/id_ed25519
Enter passphrase for /home/maxwell/.ssh/id_ed25519:
Identity added: /home/maxwell/.ssh/id_ed25519

# List added keys
$ ssh-add -l

# Delete all keys
$ ssh-add -D

# Forward agent (use local key on jump server)
$ ssh -A maxwell@bastion

Jump Server / Bastion

bash
# Through jump server
$ ssh -J jump@bastion maxwell@internal

# Multi-level jump
$ ssh -J jump1@host1,jump2@host2 maxwell@target

Set in configuration

Host internal HostName 10.0.0.100 User maxwell ProxyJump bastion


## Security Best Practices

### 1. Disable Password Authentication

```bash
# /etc/ssh/sshd_config
PasswordAuthentication no

2. Disable Root Login

bash
# /etc/ssh/sshd_config
PermitRootLogin no

3. Change Default Port

bash
# /etc/ssh/sshd_config
Port 2222

4. Use Strong Keys

bash
# Use Ed25519 or RSA 4096-bit
$ ssh-keygen -t ed25519
$ ssh-keygen -t rsa -b 4096

5. Set Key Password

Generate keys with password, use SSH Agent to manage.

6. Limit Users

bash
# /etc/ssh/sshd_config
AllowUsers maxwell alice

7. Use Fail2ban

bash
$ sudo apt install fail2ban
$ sudo systemctl enable fail2ban

Troubleshooting

Debugging Connection

bash
# Verbose output
$ ssh -v maxwell@server
$ ssh -vv maxwell@server   # More detailed
$ ssh -vvv maxwell@server  # Most detailed

Common Problems

Permission Denied

bash
# Check permissions
$ ls -la ~/.ssh/
# Ensure 600 permissions

# Check server logs
$ sudo tail -f /var/log/auth.log

Connection Refused

bash
# Check if SSH service is running
$ sudo systemctl status ssh

# Check port
$ ss -tlnp | grep 22

# Check firewall
$ sudo ufw status

Host Key Verification Failed

bash
# Delete old host key
$ ssh-keygen -R 192.168.1.100

Summary

This chapter introduced SSH usage:

  • Basic connection: ssh user@host
  • Key authentication: ssh-keygen, ssh-copy-id
  • Configuration files: ~/.ssh/config
  • File transfer: scp, rsync, sftp
  • Port forwarding: Local, Remote, Dynamic
  • Security configuration: Disable passwords, disable root

SSH is a core tool for Linux server management; mastering it will greatly improve your work efficiency.


Previous chapter: Network Basics

Next chapter: Shell Scripting Basics

Content is for learning and research only.