




















SSH 服务端设置
SSH 客户端设置
连接测试
高级安全配置
常见问题排查
sudo apt update
sudo apt install openssh-server
sudo yum install openssh-server
sudo dnf install openssh-server
编辑 SSH 配置文件 /etc/ssh/sshd_config:
sudo nano /etc/ssh/sshd_config
Port 2222 # 更改默认端口,避免使用 22
PermitRootLogin no # 禁用 root 登录
PubkeyAuthentication yes # 启用公钥认证
PasswordAuthentication no # 禁用密码认证
AuthorizedKeysFile .ssh/authorized_keys # 指定公钥文件路径
ClientAliveInterval 300 # 设置空闲超时为 300 秒
ClientAliveCountMax 2 # 最多发送 2 次保活信号
AllowUsers username1 username2 # 仅允许特定用户登录
确保 ~/.ssh/authorized_keys 文件存在并包含客户端的公钥:
mkdir -p ~/.ssh
chmod 700 ~/.ssh
touch ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
允许 SSH 流量通过防火墙。
sudo ufw allow 2222/tcp
sudo ufw enable
sudo firewall-cmd --permanent --add-port=2222/tcp
sudo firewall-cmd --reload
sudo systemctl restart ssh
sudo systemctl restart sshd
在客户端生成 SSH 密钥对(推荐使用 Ed25519 算法):
ssh-keygen -t ed25519 -C "your_email@example.com"
按提示选择保存路径和设置密码(可选)。
使用 ssh-copy-id 将公钥上传到服务器:
ssh-copy-id -i ~/.ssh/id_ed25519.pub username@server_ip -p 2222
如果 ssh-copy-id 不可用,可以手动将公钥内容添加到服务器的 ~/.ssh/authorized_keys 文件中。
编辑客户端的 SSH 配置文件 ~/.ssh/config:
nano ~/.ssh/config
添加以下内容:
Host myserver
HostName server_ip
Port 2222
User username
IdentityFile ~/.ssh/id_ed25519
ServerAliveInterval 60 # 每 60 秒发送保活信号
StrictHostKeyChecking no # 首次连接时自动接受主机密钥(仅用于测试环境)
ssh myserver
/var/log/auth.log(Ubuntu/Debian)或 /var/log/secure(CentOS/RHEL)以确认认证方式为公钥认证。22 端口,改为一个高位端口(如 2222)。/etc/ssh/sshd_config 中 PasswordAuthentication 设置为 no。sudo apt install fail2ban
sudo nano /etc/fail2ban/jail.local
添加以下内容:[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
/etc/ssh/sshd_config 中使用 AllowUsers 或 AllowGroups 限制访问:AllowUsers username1 username2
AllowGroups sshusers
sudo systemctl status sshd
~/.ssh 目录权限为 700:chmod 700 ~/.ssh
~/.ssh/authorized_keys 文件权限为 600:chmod 600 ~/.ssh/authorized_keys
sudo ufw status
或sudo firewall-cmd --list-ports
通过以上最佳实践,您可以:
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。