开始输入,可搜索发票、服务、域名、工单,以及 更多...
默认的 22 端口每天都会遭到大量自动化暴力破解扫描,把 SSH 改到非标准端口并设置高强度 root 密码,是服务器上线后最基础的加固措施。本文介绍 Linux 修改 SSH 端口与 root 密码的完整步骤,包括编辑 sshd_config、在防火墙和 SELinux 中放行新端口、安全重启 sshd 以及用 passwd 修改密码。适用于 Debian/Ubuntu 与 CentOS/Rocky/AlmaLinux。
先备份 /etc/ssh/sshd_config,再查看当前 Port 配置。新版系统可能在 /etc/ssh/sshd_config.d/ 目录中还有额外的配置片段,也要一并检查,避免设置被覆盖。
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
grep -nE '^#?Port' /etc/ssh/sshd_config
grep -rn '^Port' /etc/ssh/sshd_config.d/ 2>/dev/null
用 vi 或 nano 编辑 sshd_config,去掉 Port 前面的 # 号,并新增一行新端口。建议选择 1024–65535 之间、未被其他服务占用的端口,下文以 2222 为例。过渡期间同时监听 22 和新端口。
# /etc/ssh/sshd_config - keep 22 temporarily and add the new port
Port 22
Port 2222
CentOS、Rocky、AlmaLinux 默认使用 firewalld,Ubuntu 常用 ufw。如果系统启用了防火墙却没有放行新端口,重启 sshd 后就会无法连接。未启用防火墙的系统可以跳过此步。
# CentOS / Rocky / AlmaLinux with firewalld
firewall-cmd --permanent --add-port=2222/tcp
firewall-cmd --reload
# Debian / Ubuntu with ufw
ufw allow 2222/tcp
ufw status
在 SELinux 处于 Enforcing 状态的 RHEL 系发行版上,sshd 只被允许监听特定端口,必须用 semanage 把新端口登记为 ssh_port_t,否则 sshd 会启动失败。Debian/Ubuntu 默认没有启用 SELinux,可跳过。
# Only on systems with SELinux enforcing (CentOS / Rocky / AlmaLinux)
getenforce
dnf install -y policycoreutils-python-utils
semanage port -a -t ssh_port_t -p tcp 2222
semanage port -l | grep ssh_port_t
先用 sshd -t 检查语法,没有输出即表示正确,再重启服务。注意 Ubuntu 中服务名为 ssh;Ubuntu 22.10 及以上版本默认使用 socket 激活,修改端口后还需要重新加载并重启 ssh.socket。最后用 ss 确认新端口已在监听。
# Check syntax first - no output means OK
sshd -t
# CentOS / Rocky / AlmaLinux / Debian
systemctl restart sshd
# Ubuntu (service is named "ssh"); on Ubuntu 22.10+ with socket activation also run:
systemctl restart ssh
systemctl daemon-reload && systemctl restart ssh.socket
ss -tlnp | grep -E ':22 |:2222 '
在本地新开一个终端窗口,用新端口登录。确认成功后,从 sshd_config 中删除 Port 22 这一行并重启 sshd,然后在防火墙中移除 22 端口的放行规则。
# From your own computer, in a NEW window
ssh -p 2222 [email protected]
# After it works: remove "Port 22" from sshd_config, restart sshd, then close 22
firewall-cmd --permanent --remove-service=ssh && firewall-cmd --reload # firewalld
ufw delete allow 22/tcp # ufw (if a rule exists)
执行 passwd 后按提示输入两次新密码,屏幕不会显示字符。建议使用 12 位以上、包含大小写字母、数字和符号的随机密码,并保存在密码管理器中。批量或脚本场景可使用 chpasswd。
# Change the root password interactively
passwd root
# Or non-interactively (avoid leaving it in shell history on shared systems)
echo 'root:N3w-Str0ng-P@ssw0rd' | chpasswd
多数是防火墙或 SELinux 没有放行。通过 VNC 控制台登录,执行 ss -tlnp | grep sshd 确认 sshd 是否监听新端口,再检查 firewall-cmd --list-all 或 ufw status 的输出。
不会。系统内修改的密码不会同步到客户中心,请自行妥善保存。如果忘记密码,可以通过 VNC 控制台进入单用户模式重置,或提交工单协助。
改端口能显著减少扫描噪音,但更推荐配合 SSH 密钥登录并禁用密码登录,同时安装 fail2ban 限制暴力破解。
如按以上步骤操作后仍无法解决,欢迎提交工单联系 IMIDC 7×24 技术支持。提交时请注明服务器 IP、操作系统、已执行的命令和报错截图,工程师可以更快定位问题。