centos测试/etc/sshd/sshd_config配置是否正确

在 CentOS上测试 sshd_config 是否配置正常,以此来重启ssh服务等操作。


1. 检查配置语法

使用 OpenSSH 自带的命令检查配置文件语法:

1
sshd -t
  • 如果没有输出,说明配置文件语法正确。
  • 如果有错误,会显示具体行号和错误信息,例如:
/etc/ssh/sshd_config line 45: Bad configuration option: AllowTcpForwardingg

你可以根据提示修正。

⚠️ 注意:不要直接用 sshd -t 在生产服务器上测试后就重启,因为语法正确不代表逻辑正确,比如 Match 块里面的配置可能不生效。


2. 检查特定用户/端口的配置

如果你在 sshd_config 使用了 Match 块(例如只给某个用户开放某个端口):

1
2
3
Match User u01
Port 11506
PasswordAuthentication no

要注意:

  • Port 不能在 Match 块里面使用,sshd 会忽略并报错。
  • 可以用 sshd -T | grep u01 查看 SSH 实际应用的参数:
1
2
sshd -T | grep user
sshd -T | grep port

-T 会显示最终生效的配置。


3. 测试服务能否正常启动

1
2
3
4
5
# 测试启动
systemctl restart sshd

# 或者先测试是否能启动,不生效也不会中断
sshd -t && systemctl restart sshd

如果配置有错误,systemctl restart sshd 会失败,并且可以通过 journalctl -u sshd -xe 查看日志。


4. 实际 SSH 测试

用另一个终端尝试连接:

1
ssh -p <port> <user>@<host>

确认:

  • 用户认证方式正确(密钥或密码)。
  • 特定端口只能被指定用户使用。
  • 其他规则是否生效(禁止 shell、禁用隧道等)。

💡 总结

  • sshd -t → 检查语法。
  • sshd -T → 查看实际生效配置。
  • systemctl restart sshd → 应用配置并观察是否报错。
  • 用实际 SSH 测试连接 → 验证逻辑是否符合预期。