SSH安全加固教程:从基础配置到高级安全防护全攻略

SSH(Secure Shell)是远程服务器管理的必备工具。本教程从基础配置到安全加固,带你掌握SSH的完整使用方法。

SSH基础配置

安装 SSH 服务端

# Ubuntu/Debian
sudo apt update
sudo apt install openssh-server

# CentOS/RHEL
sudo yum install openssh-server
sudo systemctl start sshd
sudo systemctl enable sshd

修改默认端口

默认 SSH 端口 22 容易被扫描攻击,强烈建议修改:

sudo vim /etc/ssh/sshd_config

修改以下内容:

# 将 22 改为自定义端口(如 8022)
Port 8022
# 禁止 root 远程登录
PermitRootLogin no
# 允许指定用户
AllowUsers ubuntu admin
# 禁止密码登录(使用密钥更安全)
PasswordAuthentication no

重启 SSH 服务:

sudo systemctl restart sshd

密钥认证配置

生成密钥对

# 在本地计算机生成密钥
ssh-keygen -t ed25519 -C "[email protected]"
# 或使用 RSA
ssh-keygen -t rsa -b 4096 -C "[email protected]"

# 按提示完成,密钥保存在 ~/.ssh/ 目录下

部署公钥到服务器

# 方法1: 使用 ssh-copy-id
ssh-copy-id -p 8022 username@server_ip

# 方法2: 手动复制
cat ~/.ssh/id_ed25519.pub | ssh -p 8022 username@server_ip "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys"

安全防护措施

安装 fail2ban 阻止暴力破解

# 安装
sudo apt install fail2ban    # Debian/Ubuntu
sudo yum install fail2ban    # CentOS/RHEL

# 配置
sudo vim /etc/fail2ban/jail.local
[sshd]
enabled = true
port = 8022
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
sudo systemctl restart fail2ban
sudo fail2ban-client status sshd

配置 SSH 超时断开

# 编辑配置文件
sudo vim /etc/ssh/sshd_config

# 添加以下内容
ClientAliveInterval 300      # 每300秒发送一次心跳包
ClientAliveCountMax 2        # 最多2次未响应后断开
LoginGraceTime 60            # 登录超时60秒

SSH 高级用法

SSH 隧道与端口转发

# 本地端口转发
ssh -L 8080:localhost:80 user@server

# 远程端口转发
ssh -R 8080:localhost:80 user@server

# 动态端口转发(SOCKS代理)
ssh -D 1080 user@server

SSH 配置文件

# 编辑 ~/.ssh/config
vim ~/.ssh/config
Host myserver
    HostName 192.168.1.100
    Port 8022
    User ubuntu
    IdentityFile ~/.ssh/id_ed25519

Host github
    HostName github.com
    User git
    IdentityFile ~/.ssh/github_ed25519

然后就可以直接使用别名连接:

ssh myserver    # 等同于 ssh -p 8022 [email protected]

常用 SSH 命令

# 连接远程服务器
ssh username@ip

# 复制文件到远程
scp file.txt username@ip:/path/

# 递归复制目录
scp -r folder/ username@ip:/path/

# 断开连接后保持会话
ssh -t username@ip "command"     # 执行远程命令
ssh -t username@ip "tmux a"     # 进入tmux会话

故障排查

无法连接 SSH

# 检查 SSH 服务状态
sudo systemctl status sshd

# 检查防火墙
sudo ufw status          # Ubuntu
sudo firewall-cmd --list-all    # CentOS

# 检查 SSH 配置
sudo sshd -t             # 检查配置文件语法

# 查看日志
sudo tail -f /var/log/auth.log

最佳实践总结

1. 更改默认端口 — 避开 22 端口的大规模扫描

2. 使用密钥认证 — 摒弃密码登录,杜绝暴力破解

3. 禁止 root 登录 — 使用普通用户 + sudo

4. 安装 fail2ban — 自动封禁恶意 IP

5. 定期更新系统 — 保持 SSH 版本最新

6. 使用 SSH 证书 — 多主机管理更安全

写在最后

SSH安全防护是一个层层加强的过程。从基础的端口修改和密钥认证,到 fail2ban 自动防御,再到进阶的隧道技术,每一个步骤都能显著提升服务器的安全性。

建议新手按照教程一步步配置,确保能够正常登录后再逐步添加安全措施。

💡 温馨提示: 修改 SSH 配置前,请务必确保至少还有一条可以登录服务器的途径(如 VNC/网页终端),否则可能会被锁在外面。

发表评论