CentOS 配置 SSH 服务指南 🔐
📋 目录导航
🌟 简介 本指南将帮助您在 CentOS 系统上配置 SSH 服务器,提高安全性和连接稳定性。
🔧 一、安装和更新 SSH 服务 1. 📦 更新系统并安装 OpenSSH 服务器 1 yum -y update && yum install -y openssl openssh-server
2. 📝 查看 SSH 配置文件 1 cat /etc/ssh/sshd_config
⚙️ 二、配置 SSH 服务器 1. ⚡ 修改 SSH 配置文件并重启服务 1 2 3 4 5 sed -i.bak -e '/Port 22/ a Port 22' -e '/PermitRootLogin/ a PermitRootLogin yes' -e '/ClientAliveInterval/ a ClientAliveInterval 10' -e '/ClientAliveCountMax/ a ClientAliveCountMax 999' /etc/ssh/sshd_config systemctl restart sshd && hostname -I
2. 📋 配置修改说明
原配置
修改后配置
说明
#Port 22
Port 22
启用 SSH 端口 22
#PermitRootLogin prohibit-password
PermitRootLogin yes
允许 root 用户登录
#ClientAliveInterval 0
ClientAliveInterval 10
每10秒发送一次保活信号
#ClientAliveCountMax 3
ClientAliveCountMax 999
允许999次保活信号无响应
🛡️ 三、增强 SSH 安全性(推荐) 1. 🔒 进一步安全配置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backupcat >> /etc/ssh/sshd_config << EOF # 安全增强配置 Protocol 2 MaxAuthTries 3 MaxSessions 10 LoginGraceTime 60 PermitEmptyPasswords no X11Forwarding no EOF systemctl restart sshd
2. 🔥 配置防火墙 1 2 3 4 5 6 systemctl status firewalld firewall-cmd --permanent --add-service=ssh firewall-cmd --reload
🔍 四、验证配置 1. 📊 检查 SSH 服务状态
2. 🧪 测试 SSH 连接 从另一台机器测试连接:
1 ssh username@your_server_ip
3. 👀 查看当前配置 1 2 3 4 5 sshd -T netstat -tlnp | grep ssh
💡 五、高级配置选项 1. 🔄 更改默认 SSH 端口(增强安全性) 1 2 3 4 5 6 7 8 9 10 sed -i 's/^#Port 22/Port 2222/' /etc/ssh/sshd_config firewall-cmd --permanent --remove-service=ssh firewall-cmd --permanent --add-port=2222/tcp firewall-cmd --reload systemctl restart sshd
2. 🔑 使用密钥认证(推荐) 1 2 3 4 5 6 7 8 9 ssh-keygen -t rsa -b 4096 ssh-copy-id username@your_server_ip sed -i 's/^#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config systemctl restart sshd
3. 👥 限制用户访问 1 2 3 4 5 6 7 echo "AllowUsers username1 username2" >> /etc/ssh/sshd_configecho "DenyUsers username3" >> /etc/ssh/sshd_configsystemctl restart sshd
🚨 六、故障排除 1. ❌ 如果无法连接 1 2 3 4 5 6 7 8 9 10 11 systemctl status sshd netstat -tlnp | grep :22 firewall-cmd --list-all tail -f /var/log/secure
2. 🔄 恢复配置 如果配置出错,可以恢复备份:
1 2 cp /etc/ssh/sshd_config.bak /etc/ssh/sshd_configsystemctl restart sshd
📊 七、SSH 配置参数说明
参数
说明
推荐值
Port
SSH 监听端口
22 或自定义高端口
PermitRootLogin
是否允许 root 登录
no
(更安全)或 yes
ClientAliveInterval
服务器向客户端发送保活消息的时间间隔
30-60
ClientAliveCountMax
服务器在断开连接之前未收到客户端响应的保活消息数量
3-5
MaxAuthTries
最大认证尝试次数
3
PasswordAuthentication
是否允许密码认证
no
(推荐使用密钥)
Protocol
SSH 协议版本
2
🔒 八、安全最佳实践
🔑 使用密钥认证 :禁用密码认证,使用 SSH 密钥对
🔄 更改默认端口 :减少自动化攻击
👥 限制用户访问 :只允许必要的用户通过 SSH 访问
🔥 使用防火墙 :限制 SSH 端口的访问来源
🔄 定期更新 :保持系统和 SSH 软件包最新
📝 监控日志 :定期检查 SSH 登录尝试
🛡️ 使用 Fail2ban :安装 Fail2ban 防止暴力破解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 yum install -y epel-release yum install -y fail2ban cat > /etc/fail2ban/jail.local << EOF [sshd] enabled = true port = ssh logpath = /var/log/secure maxretry = 3 bantime = 3600 EOF systemctl enable fail2ban systemctl start fail2ban
🚀 通过以上配置,您的 CentOS SSH 服务器将更加安全可靠。记得在修改配置前备份原文件,并在生产环境中谨慎更改安全设置!