Ubuntu SSH安全设置关键步骤
确保系统及SSH软件包为最新版本,修复已知安全漏洞:
sudo apt update && sudo apt upgrade -y
sudo apt install openssh-server -y
修改/etc/ssh/sshd_config文件,取消#Port 22注释并替换为非标准端口(如2222):
sudo nano /etc/ssh/sshd_config
# 找到#Port 22,修改为Port 2222(或其他未被使用的端口)
保存后重启SSH服务,并通过sudo netstat -tuln | grep sshd验证端口监听状态。
在sshd_config中设置PermitRootLogin no,禁止root用户通过SSH直接登录,降低账户被爆破的风险:
sudo nano /etc/ssh/sshd_config
# 找到PermitRootLogin,修改为PermitRootLogin no
重启SSH服务使更改生效。
ssh-keygen -t ed25519 -C "your_email@example.com" # 或ssh-keygen -t rsa -b 4096
ssh-copy-id自动复制公钥到服务器的~/.ssh/authorized_keys文件:ssh-copy-id -p 2222 your_username@server_ip # 替换为新端口和用户名
sshd_config中启用公钥认证并禁用密码认证:sudo nano /etc/ssh/sshd_config
# 确保以下两行设置正确
PubkeyAuthentication yes
PasswordAuthentication no
重启SSH服务后,仅能通过密钥登录。通过AllowUsers指令指定可登录的用户名(如仅允许admin用户登录):
sudo nano /etc/ssh/sshd_config
# 添加或修改为以下内容(根据需求调整)
AllowUsers your_username
重启SSH服务应用限制。
使用UFW(Uncomplicated Firewall)仅允许特定IP地址访问SSH端口(如2222):
sudo ufw allow from 192.168.1.100 to any port 2222 # 替换为你的客户端IP
sudo ufw enable # 启用防火墙
sudo ufw reload # 重新加载规则
若未使用UFW,可通过iptables添加类似规则。
Fail2Ban可监控SSH日志,自动封禁多次登录失败的IP地址:
sudo apt install fail2ban -y
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local # 备份默认配置
sudo nano /etc/fail2ban/jail.local
在[ssh]部分修改以下参数(端口替换为新端口):
[ssh]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/auth.log
maxretry = 3 # 允许的最大失败次数
bantime = 600 # 封禁时间(秒)
重启Fail2Ban服务:
sudo systemctl restart fail2ban
sudo apt update && sudo apt upgrade保持系统和SSH软件包最新,修复安全漏洞。/var/log/auth.log文件,查看可疑登录尝试(如频繁失败登录),及时采取措施。