2.6.2 SSH服务配置与常用参数
SSH 服务端配置以 /etc/ssh/sshd_config 为核心,修改后需重载或重启服务使其生效。配置时应兼顾可用性与安全性,并结合网络拓扑、账号体系与访问策略进行优化。
原理草图(连接与认证流程):
安装与服务管理(不同发行版):
# Debian/Ubuntu
sudo apt-get update
sudo apt-get install -y openssh-server
# RHEL/CentOS/Rocky
sudo yum install -y openssh-server
sudo systemctl enable --now sshd
# 查看状态
systemctl status sshd
核心配置文件与常用命令:
- 服务端配置:/etc/ssh/sshd_config
- 客户端配置:/etc/ssh/ssh_config
- 语法检查:sshd -t
- 查看生效配置:sshd -T
- 平滑重载:systemctl reload sshd
- 重启服务:systemctl restart sshd
常用参数与说明(关键命令解释):
- Port 22:监听端口;改为非默认端口降低扫描风险(需放行防火墙端口)。
- ListenAddress 0.0.0.0:绑定监听地址;可指定管理网 IP。
- Protocol 2:仅使用 SSHv2。
- PermitRootLogin no:禁止 root 直接登录。
- PasswordAuthentication no:禁用密码登录,配合密钥登录。
- PubkeyAuthentication yes:启用公钥认证。
- AuthorizedKeysFile .ssh/authorized_keys:公钥文件路径。
- MaxAuthTries 3:限制单次连接认证失败次数。
- LoginGraceTime 60:登录超时。
- ClientAliveInterval 300 + ClientAliveCountMax 2:空闲连接保活与断开。
- AllowUsers / DenyUsers:按用户白/黑名单控制。
- AllowGroups / DenyGroups:按用户组控制。
- UseDNS no:禁用反向解析加快登录。
- GSSAPIAuthentication no:关闭 GSSAPI 认证。
- LogLevel VERBOSE:提高日志详细度便于审计。
- Banner /etc/issue.net:登录提示与法律声明。
推荐配置示例(完整可执行,含注释):
# /etc/ssh/sshd_config
Port 2222
ListenAddress 10.0.0.10
Protocol 2
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
MaxAuthTries 3
LoginGraceTime 60
ClientAliveInterval 300
ClientAliveCountMax 2
AllowGroups ops admin
UseDNS no
GSSAPIAuthentication no
LogLevel VERBOSE
Banner /etc/issue.net
配置生效与验证流程(带预期效果):
# 1) 语法检查
sudo sshd -t
# 预期:无输出表示通过
# 2) 平滑加载配置
sudo systemctl reload sshd
# 3) 新终端验证登录(新端口)
ssh -p 2222 user@10.0.0.10
# 预期:成功登录且无密码提示(密钥登录)
# 4) 查看生效配置
sudo sshd -T | egrep 'port|listenaddress|passwordauthentication|pubkeyauthentication|permitrootlogin|allowgroups'
配套防火墙放行示例:
# firewalld
sudo firewall-cmd --permanent --add-port=2222/tcp
sudo firewall-cmd --reload
# nftables 示例
sudo nft add rule inet filter input tcp dport 2222 accept
常见排错与定位(含命令解释):
# 1) 连接被拒绝:确认端口监听
sudo ss -lntp | grep sshd
# 预期:0.0.0.0:2222 或 10.0.0.10:2222
# 2) 认证失败:查看日志
sudo tail -f /var/log/secure
# 预期:看到 "Accepted publickey" 或 "Failed password"
# 3) 配置错误导致服务起不来
sudo sshd -t
sudo journalctl -u sshd -xe
练习与实操任务:
1) 将 SSH 端口改为 2222,限制仅 ops 组可登录,并验证生效配置。
2) 禁用密码登录,配置密钥登录后测试无密码登录成功。
3) 将 ClientAliveInterval 设置为 120,观察空闲断开行为。
4) 开启 LogLevel VERBOSE,在日志中确认公钥指纹记录。