sshd_config 是 OpenSSH 服务器的主要配置文件,位于 /etc/ssh/sshd_config
。以下是一份详细的配置指南:
更改默认端口:
Port 2222 # 改为非标准端口(1024-65535)
禁用 root 登录:
PermitRootLogin no
限制用户访问:
AllowUsers user1 user2 # 只允许特定用户
# 或
AllowGroups sshusers # 只允许特定组
禁用密码认证(推荐使用密钥):
PasswordAuthentication no
限制登录尝试:
MaxAuthTries 3
LoginGraceTime 1m
空闲会话超时:
ClientAliveInterval 300
ClientAliveCountMax 0
禁用不安全的协议和算法:
Protocol 2
Ciphers aes256-ctr,aes192-ctr,aes128-ctr
MACs hmac-sha2-512,hmac-sha2-256
限制监听接口:
ListenAddress 192.168.1.100 # 只监听特定IP
启用 X11 转发(如果需要):
X11Forwarding yes
SFTP 子系统配置:
Subsystem sftp /usr/lib/openssh/sftp-server
# 或限制SFTP用户到特定目录
Subsystem sftp internal-sftp
Match Group sftpusers
ChrootDirectory /home/%u
ForceCommand internal-sftp
AllowTcpForwarding no
X11Forwarding no
端口转发:
AllowTcpForwarding yes # 或no禁用
GatewayPorts no
LogLevel VERBOSE
修改配置后,需要重启 SSH 服务:
sudo systemctl restart sshd
# 或
sudo service ssh restart
检查配置语法:
sudo sshd -t
查看当前生效的配置:
sudo sshd -T
修改前备份原配置文件:
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
使用 fail2ban 防止暴力破解
定期更新 OpenSSH 到最新版本
使用 SSH 密钥认证而非密码认证
考虑使用两步验证增强安全性
注意:配置更改后,确保不会将自己锁在系统外。建议在另一个终端保持活动会话,或使用类似 screen/tmux 的工具。