在 CentOS 系统中配置 SSH 主要包括 安装 SSH 服务、启动服务、配置端口/安全策略、开放防火墙端口、设置开机自启 等步骤。下面分别说明 CentOS 7 / 8 / Stream 的常用做法(差异不大)。
CentOS 通常默认已安装,如未安装可手动安装:
sudo yum install -y openssh-server
CentOS 8 / Stream 可用
dnf:
sudo dnf install -y openssh-server
sudo systemctl start sshd
sudo systemctl enable sshd
sudo systemctl status sshd
看到 active (running) 表示正常运行。
SSH 配置文件路径:
/etc/ssh/sshd_config
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
sudo vi /etc/ssh/sshd_config
| 配置项 | 说明 | 建议 |
|---|---|---|
Port 22 |
默认端口 | 可改为其他端口(如 2222) |
PermitRootLogin |
是否允许 root 登录 | no ✅ |
PasswordAuthentication |
密码登录 | no(配合密钥) |
PubkeyAuthentication |
密钥登录 | yes ✅ |
UseDNS |
反向解析 | no(加快连接) |
MaxAuthTries |
最大尝试次数 | 3 |
示例:
Port 2222
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
UseDNS no
MaxAuthTries 3
sudo systemctl restart sshd
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --reload
sudo firewall-cmd --permanent --add-port=2222/tcp
sudo firewall-cmd --reload
sudo firewall-cmd --list-all
ssh-keygen -t rsa -b 4096
ssh-copy-id user@server_ip
或手动:
cat ~/.ssh/id_rsa.pub | ssh user@server_ip "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
如果修改了 SSH 端口:
sudo semanage port -a -t ssh_port_t -p tcp 2222
查看端口是否生效:
semanage port -l | grep ssh
ssh user@server_ip -p 2222
PubkeyAuthentication 被禁用如果你愿意,我可以:
只要告诉我你的 CentOS 版本和使用场景即可。