温馨提示×

CentOS如何安装SSH服务

小樊
79
2026-07-07 23:06:32
栏目: 智能运维

在 CentOS 上安装并启用 SSH 服务(通常是 OpenSSH)的步骤如下,适用于 CentOS 7 / 8 / Stream


一、检查是否已安装 SSH

rpm -qa | grep openssh

systemctl status sshd

如果显示 sshd 服务信息,说明已安装。


二、安装 OpenSSH 服务

CentOS 7

yum install -y openssh-server

CentOS 8 / Stream

dnf install -y openssh-server

三、启动并设置开机自启

systemctl start sshd
systemctl enable sshd

检查状态:

systemctl status sshd

看到 active (running) 表示正常运行。


四、配置防火墙(非常重要)

1️⃣ 开放 22 端口(SSH 默认端口)

firewalld(CentOS 默认)

firewall-cmd --permanent --add-service=ssh
firewall-cmd --reload

iptables(老系统)

iptables -I INPUT -p tcp --dport 22 -j ACCEPT
service iptables save

五、确认 SSH 端口监听

ss -lntp | grep ssh

netstat -lntp | grep ssh

六、修改 SSH 配置(可选但推荐)

配置文件路径:

/etc/ssh/sshd_config

常见安全优化:

Port 2222                 # 修改默认端口
PermitRootLogin no        # 禁止 root 远程登录
PasswordAuthentication yes

修改后重启服务:

systemctl restart sshd

⚠️ 修改端口后,防火墙也要放行新端口。


七、测试连接

从另一台机器连接:

ssh 用户名@服务器IP

如果修改了端口:

ssh -p 2222 用户名@服务器IP

八、常见问题

❌ 连接被拒绝

  • sshd 未启动
  • 防火墙未放行端口
  • 云服务器安全组未放行 22 端口

❌ 登录慢

UseDNS no
GSSAPIAuthentication no

如果你告诉我:

  • CentOS 具体版本
  • 是物理机 / 虚拟机 / 云服务器
  • 是否使用密钥登录

我可以给你更精确的配置方案 ✅

0