SSH 服务器完全指南 / 第2章 安装与初始配置
第2章 安装与初始配置
2.1 安装前的准备
在安装 SSH 服务器之前,需要确认以下事项:
| 检查项 | 说明 |
|---|---|
| 系统版本 | 确认操作系统及版本 |
| 网络连通 | 确保能访问服务器(控制台或已有 SSH) |
| 防火墙 | 了解当前防火墙规则 |
| 端口占用 | 确认 22 端口未被占用 |
| root/sudo 权限 | 安装软件需要管理员权限 |
# 检查系统版本
cat /etc/os-release
# 检查是否已安装 OpenSSH
which sshd
sshd -V 2>&1 | head -5
# 检查端口占用
ss -tlnp | grep :22
2.2 Debian / Ubuntu 安装
安装 OpenSSH Server
# 更新软件包列表
sudo apt update
# 安装 OpenSSH 服务器
sudo apt install -y openssh-server
# 确认安装
dpkg -l | grep openssh-server
启动与自启
# 启动 SSH 服务
sudo systemctl start sshd
# 设置开机自启
sudo systemctl enable sshd
# 检查服务状态
sudo systemctl status sshd
正常输出应类似:
● ssh.service - OpenBSD Secure Shell Server
Loaded: loaded (/lib/systemd/system/ssh.service; enabled; vendor preset: enabled)
Active: active (running) since Mon 2025-01-01 10:00:00 CST; 1min ago
Process: 1234 ExecStartPre=/usr/sbin/sshd -t (code=exited, status=0/SUCCESS)
Main PID: 1235 (sshd)
Tasks: 1 (limit: 4567)
Memory: 2.1M
CPU: 15ms
CGroup: /system.slice/ssh.service
└─1235 "sshd: /usr/sbin/sshd [listener] 0 of 10-100 startups"
防火墙配置(UFW)
# 查看 UFW 状态
sudo ufw status
# 允许 SSH(如果 UFW 已启用)
sudo ufw allow ssh
# 或者指定端口
sudo ufw allow 22/tcp
# 如果自定义了端口
sudo ufw allow 2222/tcp
# 重新加载规则
sudo ufw reload
2.3 RHEL / CentOS / Rocky Linux 安装
安装 OpenSSH Server
# RHEL/CentOS 通常已预装,如果没有:
sudo yum install -y openssh-server
# 或者在较新版本中使用 dnf
sudo dnf install -y openssh-server
启动与自启
# 启动服务
sudo systemctl start sshd
# 设置开机自启
sudo systemctl enable sshd
# 检查状态
sudo systemctl status sshd
防火墙配置(firewalld)
# 查看防火墙状态
sudo firewall-cmd --state
# 添加 SSH 服务
sudo firewall-cmd --permanent --add-service=ssh
# 如果使用自定义端口
sudo firewall-cmd --permanent --add-port=2222/tcp
# 重载规则
sudo firewall-cmd --reload
# 验证规则
sudo firewall-cmd --list-all
SELinux 注意事项
如果使用自定义端口,需要更新 SELinux 策略:
# 查看当前 SSH 端口
sudo semanage port -l | grep ssh
# 添加自定义端口
sudo semanage port -a -t ssh_port_t -p tcp 2222
# 验证
sudo semanage port -l | grep ssh
2.4 Arch Linux 安装
# 安装 OpenSSH
sudo pacman -S openssh
# 启动服务
sudo systemctl start sshd
# 开机自启
sudo systemctl enable sshd
# Arch 使用 iptables 或 nftables,检查规则
sudo iptables -L -n
2.5 macOS 安装
macOS 自带 OpenSSH 客户端,但服务端需要手动启用:
# 方法一:系统偏好设置
# 系统偏好设置 → 共享 → 远程登录 → 勾选启用
# 方法二:命令行
sudo systemsetup -setremotelogin on
# 停止 SSH 服务
sudo systemsetup -setremotelogin off
# 查看状态
sudo systemsetup -getremotelogin
配置文件位置:/etc/ssh/sshd_config
macOS 特殊配置
# macOS 特有的配置选项
# /etc/ssh/sshd_config
# 启用 X11 转发(需要安装 XQuartz)
X11Forwarding yes
# macOS 使用不同的 PAM 配置
# 使用 AuthorizationDB 进行认证
UsePAM yes
2.6 FreeBSD 安装
# FreeBSD 自带 OpenSSH,编辑 /etc/rc.conf 启用
echo 'sshd_enable="YES"' | sudo tee -a /etc/rc.conf
# 启动服务
sudo service sshd start
# 配置文件
sudo vi /etc/ssh/sshd_config
2.7 Windows 安装
Windows 10/11 / Windows Server 2019+
Windows 从 1809 版本开始内置 OpenSSH:
# 检查是否已安装
Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH*'
# 安装 OpenSSH 服务器
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
# 启动 SSH 服务
Start-Service sshd
# 设置开机自启
Set-Service -Name sshd -StartupType 'Automatic'
# 确认防火墙规则(通常已自动创建)
Get-NetFirewallRule -Name *ssh*
# 如果没有防火墙规则
New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
配置文件位置
# Windows SSH 配置文件
C:\ProgramData\ssh\sshd_config
# 用户密钥目录
C:\Users\<username>\.ssh\
# 服务密钥目录
C:\ProgramData\ssh\
2.8 初始安全配置
安装完成后,在开放网络访问之前,应立即进行基础安全配置。
创建备份
# 备份原始配置文件
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup.$(date +%Y%m%d)
# 记录当前配置
sudo cat /etc/ssh/sshd_config | grep -v '^#' | grep -v '^$' > ~/sshd_config_effective.txt
最小化初始配置
编辑 /etc/ssh/sshd_config:
sudo vi /etc/ssh/sshd_config
推荐的初始配置:
# /etc/ssh/sshd_config - 初始安全配置
# ===== 基本设置 =====
# 监听端口(可选修改,减少自动化扫描噪音)
Port 22
# 仅监听 IPv4(根据需要调整)
AddressFamily inet
# 监听所有接口,或指定具体 IP
ListenAddress 0.0.0.0
# 协议版本(OpenSSH 7.4+ 仅支持 SSH-2)
Protocol 2
# 主机密钥
HostKey /etc/ssh/ssh_host_ed25519_key
HostKey /etc/ssh/ssh_host_rsa_key
# ===== 认证设置 =====
# 允许密钥认证
PubkeyAuthentication yes
# 允许密码认证(初期保留,配好密钥后关闭)
PasswordAuthentication yes
# 禁止空密码
PermitEmptyPasswords no
# 禁止 root 密码登录(允许密钥登录)
PermitRootLogin prohibit-password
# 最大认证尝试次数
MaxAuthTries 3
# ===== 会话设置 =====
# 登录超时时间(秒)
LoginGraceTime 60
# 最大并发会话数
MaxSessions 10
# 客户端活跃检测
ClientAliveInterval 300
ClientAliveCountMax 2
# ===== 日志 =====
SyslogFacility AUTH
LogLevel INFO
# ===== 安全限制 =====
# 禁用不安全的功能
X11Forwarding no
AllowTcpForwarding no
PermitTunnel no
# 禁用 GSSAPI(除非你使用 Kerberos)
GSSAPIAuthentication no
检查配置语法
# 测试配置文件语法(必须执行,错误的配置可能导致无法连接)
sudo sshd -t
# 如果没有输出,说明配置正确
# 如果有错误,会显示具体行号和错误信息
应用配置
# 方法一:重启服务(会断开所有现有连接)
sudo systemctl restart sshd
# 方法二:重新加载配置(推荐,不会断开现有连接)
sudo systemctl reload sshd
# 验证配置已生效
sudo systemctl status sshd
⚠️ 警告: 在修改 SSH 配置时,始终保持一个现有的 SSH 连接不要断开,直到验证新配置正常工作。否则配置错误可能将你锁在服务器外面。
2.9 生成主机密钥
主机密钥用于标识服务器身份,防止中间人攻击(MITM)。
# 查看现有主机密钥
ls -la /etc/ssh/ssh_host_*
# 如果密钥不存在或需要重新生成
sudo ssh-keygen -A
# 推荐的主机密钥类型
# Ed25519(首选)
sudo ssh-keygen -t ed25519 -f /etc/ssh/ssh_host_ed25519_key -N ""
# RSA 4096(兼容性)
sudo ssh-keygen -t rsa -b 4096 -f /etc/ssh/ssh_host_rsa_key -N ""
# 可选:删除不安全的旧密钥
sudo rm -f /etc/ssh/ssh_host_dsa_key*
sudo rm -f /etc/ssh/ssh_host_ecdsa_key*
主机密钥文件权限:
# 私钥:仅 root 可读
sudo chmod 600 /etc/ssh/ssh_host_*_key
sudo chown root:root /etc/ssh/ssh_host_*_key
# 公钥:所有人可读
sudo chmod 644 /etc/ssh/ssh_host_*_key.pub
sudo chown root:root /etc/ssh/ssh_host_*_key.pub
2.10 验证安装
本地验证
# 检查 SSH 服务是否在监听
sudo ss -tlnp | grep sshd
# 预期输出(类似):
# LISTEN 0 128 0.0.0.0:22 0.0.0.0:* users:(("sshd",pid=1235,fd=3))
# 检查进程
ps aux | grep sshd
# 查看 SSH 版本
ssh -V
远程测试
# 从另一台机器连接测试
ssh user@server-ip -v
# 查看服务器支持的算法
ssh -Q cipher # 查看支持的加密算法
ssh -Q mac # 查看支持的 MAC 算法
ssh -Q kex # 查看支持的密钥交换算法
ssh -Q key # 查看支持的密钥类型
使用 ssh-audit 进行安全审计
# 安装 ssh-audit
pip install ssh-audit
# 或
sudo apt install ssh-audit
# 运行审计
ssh-audit localhost
# 输出示例:
# [info] Banner: SSH-2.0-OpenSSH_9.0 Ubuntu-3ubuntu0.1
# [info] Key exchange algorithms:
# curve25519-sha256 -- [info] Available
# diffie-hellman-group16-sha512 -- [info] Available
# diffie-hellman-group14-sha256 -- [info] Available
# [info] Authentication algorithms:
# ssh-ed25519 -- [info] Available
# rsa-sha2-512 -- [info] Available
# [warning] ssh-dss -- [warn] Weak algorithm
2.11 日志配置
systemd 系统(journald)
# 查看 SSH 相关日志
sudo journalctl -u sshd -f
# 查看最近 100 条 SSH 日志
sudo journalctl -u sshd -n 100
# 按时间过滤
sudo journalctl -u sshd --since "2025-01-01" --until "2025-01-02"
# 查看认证失败
sudo journalctl -u sshd | grep "Failed password"
传统日志文件
# Debian/Ubuntu
sudo tail -f /var/log/auth.log
# RHEL/CentOS
sudo tail -f /var/log/secure
# FreeBSD
sudo tail -f /var/log/auth.log
配置日志级别
# /etc/ssh/sshd_config
# 日志级别选项:
# QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG, DEBUG1, DEBUG2, DEBUG3
LogLevel INFO
# 推荐:生产环境使用 INFO,排查问题时临时用 VERBOSE
# DEBUG 级别会产生大量日志,仅在排查时使用
2.12 常见安装问题
问题一:端口被占用
# 错误信息:
# sshd: error: bind to port 22: Address already in use
# 查找占用端口的进程
sudo ss -tlnp | grep :22
# 或
sudo lsof -i :22
# 解决方案:停止占用进程或更改 SSH 端口
问题二:配置文件语法错误
# 错误信息:
# /etc/ssh/sshd_config: line XX: Bad configuration option
# 检查语法
sudo sshd -t
# 修复后重新加载
sudo systemctl reload sshd
问题三:防火墙阻止连接
# 从外部连接超时,但从本地可以
# 检查防火墙状态
sudo ufw status verbose # Ubuntu/Debian
sudo firewall-cmd --list-all # RHEL/CentOS
# 临时禁用防火墙测试(仅用于排查,测试后立即恢复)
sudo ufw disable # Ubuntu/Debian
sudo systemctl stop firewalld # RHEL/CentOS
问题四:密钥文件权限错误
# 错误信息:
# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
# @ WARNING: UNPROTECTED PRIVATE KEY FILE! @
# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
# Permissions 0644 for '/etc/ssh/ssh_host_ed25519_key' are too open.
# 修复权限
sudo chmod 600 /etc/ssh/ssh_host_*_key
sudo chmod 644 /etc/ssh/ssh_host_*_key.pub
sudo chown root:root /etc/ssh/ssh_host_*
扩展阅读
下一章: 第3章 密钥对与基本连接 → 学习生成密钥对、使用 SSH 客户端和配置连接。