- Published on
SSH 服务器安装与配置
- Authors
- Name
- Yvan Yang
SSH 服务器安装与配置
- 安装 SSH 服务器
# 安装 openssh-server
sudo apt update
sudo apt install openssh-server
# 检查服务状态
sudo systemctl status ssh
- 主要配置文件
# SSH 服务器配置文件位置
/etc/ssh/sshd_config
# 常用配置项
Port 22 # SSH 端口号
PermitRootLogin no # 禁止 root 直接登录
PasswordAuthentication yes # 是否允许密码认证
PubkeyAuthentication yes # 是否允许密钥认证
- 修改配置后重启服务
sudo systemctl restart ssh
SSH 密钥认证设置
- 生成 SSH 密钥对
# 在客户端生成密钥对
ssh-keygen -t ed25519 -C "your_email@example.com"
# 使用 RSA (如果需要更广泛的兼容性)
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
- 将公钥复制到服务器
# 方法一:使用 ssh-copy-id
ssh-copy-id username@remote_host
# 方法二:手动复制
cat ~/.ssh/id_ed25519.pub | ssh username@remote_host "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
SSH 登录方法
- 基本登录命令
# 使用密码登录
ssh username@hostname
# 指定端口登录
ssh -p 2222 username@hostname
# 使用密钥登录(自动选择密钥)
ssh username@hostname
- 使用配置文件简化登录
# 编辑 ~/.ssh/config 文件
Host myserver
HostName server.example.com
User username
Port 22
IdentityFile ~/.ssh/id_ed25519
# 使用简化命令登录
ssh myserver
安全加固建议
- 修改默认端口
# 在 sshd_config 中修改
Port 2222
- 禁用密码认证(仅使用密钥认证)
# 在 sshd_config 中设置
PasswordAuthentication no
- 限制允许登录的用户
# 在 sshd_config 中添加
AllowUsers user1 user2
- 配置登录失败处理
# 在 sshd_config 中设置
MaxAuthTries 3
LoginGraceTime 30
- 设置空闲超时
# 在 sshd_config 中设置
ClientAliveInterval 300
ClientAliveCountMax 3
常见问题处理
- 权限问题
# 设置正确的文件权限
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
- 连接故障排查
# 使用详细输出模式
ssh -v username@hostname
# 检查服务器日志
sudo tail -f /var/log/auth.log
- 密钥认证失败
# 检查服务器端密钥权限
ls -la ~/.ssh/
ls -la ~/.ssh/authorized_keys
# 检查客户端私钥权限
ls -la ~/.ssh/id_ed25519
记住在进行任何配置更改后都要重启 SSH 服务:
sudo systemctl restart ssh