什么是 OpenSSH?
OpenSSH(Open Secure Shell)是一套用于安全远程登录和其他网络服务的安全工具。 它通过加密通信防止窃听、连接劫持和其他攻击,是 Linux 系统管理中最常用的工具之一。
在 Ubuntu / Debian 上安装 OpenSSH
大多数现代 Ubuntu 或 Debian 系统默认已安装 OpenSSH 客户端,但可能未安装服务端。
如果你需要让其他机器通过 SSH 连接到你的 Ubuntu/Debian 主机,请安装 openssh-server。
# 更新软件包列表
sudo apt update
# 安装 OpenSSH 服务端
sudo apt install openssh-server
# 启动并设置开机自启
sudo systemctl start ssh
sudo systemctl enable ssh
在 CentOS / RHEL / Rocky Linux 上安装 OpenSSH
这些系统通常预装了 OpenSSH,但若未安装或被移除,可使用以下命令:
# 安装 OpenSSH 服务端(RHEL/CentOS 7+ 使用 openssh-server)
sudo yum install -y openssh-server
# 或对于使用 dnf 的新版本(如 CentOS Stream、Rocky Linux 8+)
sudo dnf install -y openssh-server
# 启动服务并启用开机自启
sudo systemctl start sshd
sudo systemctl enable sshd
验证 SSH 服务是否运行
运行以下命令检查 SSH 服务状态:
sudo systemctl status ssh # Ubuntu/Debian
sudo systemctl status sshd # CentOS/RHEL
你也可以检查 SSH 是否监听 22 端口:
ss -tuln | grep :22
防火墙设置(如启用)
确保防火墙允许 SSH 流量(默认端口 22):
Ubuntu (UFW)
sudo ufw allow ssh
CentOS / RHEL (firewalld)
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --reload
常见问题
- 无法连接? 检查服务是否运行、防火墙是否放行、SELinux(如适用)是否阻止。
- 修改默认端口? 编辑
/etc/ssh/sshd_config,修改Port行,然后重启服务。 - 禁用密码登录? 在
sshd_config中设置PasswordAuthentication no并使用密钥认证。