📋 完整流程图
检查系统版本 → 安装 OpenSSH → 启动服务 → 启用自启 → 验证状态 → 配置防火墙
一、检查系统版本
bash
cat /etc/os-release
| 发行版 | 服务名称 | 安装工具 |
|---|---|---|
| Ubuntu/Debian | ssh |
apt |
| RHEL/CentOS/Fedora/Rocky | sshd |
dnf/yum |
| Arch Linux | sshd |
pacman |
二、安装 OpenSSH 服务器
Ubuntu/Debian
bash
sudo apt update
sudo apt install openssh-server -y
RHEL/CentOS/Fedora/Rocky
bash
sudo dnf install openssh-server -y
# 旧版本用:sudo yum install openssh-server -y
Arch Linux
bash
sudo pacman -S openssh
三、启动 SSH 服务
bash
# Ubuntu/Debian
sudo systemctl start ssh
# RHEL/CentOS/Fedora/Arch
sudo systemctl start sshd
四、设置开机自启
bash
# Ubuntu/Debian
sudo systemctl enable ssh
# RHEL/CentOS/Fedora/Arch
sudo systemctl enable sshd
五、验证状态
bash
# 查看服务状态(Ubuntu/Debian 用 ssh,其他用 sshd)
sudo systemctl status ssh
# 检查是否开机自启
sudo systemctl is-enabled ssh
# 检查端口监听
sudo ss -tlnp | grep :22
✅ 成功标志:
Active: active (running)Loaded: ... enabled;- 端口 22 处于
LISTEN状态
六、配置防火墙
UFW (Ubuntu)
bash
sudo ufw allow ssh
sudo ufw reload
firewalld (RHEL/CentOS/Fedora)
bash
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --reload
🔧 一键命令(复制即用)
Ubuntu/Debian 一键安装
bash
sudo apt update && \
sudo apt install openssh-server -y && \
sudo systemctl start ssh && \
sudo systemctl enable ssh && \
sudo ufw allow ssh && \
sudo systemctl status ssh
RHEL/CentOS/Fedora 一键安装
bash
sudo dnf install openssh-server -y && \
sudo systemctl start sshd && \
sudo systemctl enable sshd && \
sudo firewall-cmd --permanent --add-service=ssh && \
sudo firewall-cmd --reload && \
sudo systemctl status sshd
⚠️ 常见问题
| 问题 | 解决 |
|---|---|
Unit ssh.service not found |
用 sshd 代替 ssh |
Connection refused |
检查防火墙/SELinux |
| 端口冲突 | sudo lsof -i :22 |
| 启动失败 | sudo journalctl -xeu ssh 看日志 |