安装 SSH 服务
sudo apt update && sudo apt install openssh-server -y
启动服务:
sudo systemctl enable --now ssh sudo systemctl status ssh
开启防火墙的 22 端口:
sudo ufw allow ssh sudo ufw enable sudo ufw status
查看 Ubuntu 服务器的 ip:
ifconfig
修改 ssh 配置:
sudo vim /etc/ssh/sshd_config
修改其中的选项:
PubkeyAuthentication yes # 启用公钥认证
AuthorizedKeysFile .ssh/authorized_keys # 指定公钥文件路径
PermitRootLogin yes # 允许 root 登录(若需 root 连接)
PasswordAuthentication no # 可选:禁用密码登录(增强安全)
重启服务:
sudo systemctl restart ssh
配置密钥
生成 RSA 密钥对,在服务端或客户端都可以实现这一步,建议在客户端实现,然后拷贝公钥到服务端。
Linux 环境可以通过以下命令生成密钥对:
ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa -N ""
Windows 环境可以使用 Putty 工具生成,具体可以看这篇。
如果是 Windows 客户端,可能还需要转换一个 pem 私钥,同样可以通过 Putty 工具实现。
有了密钥对后,将公钥文件(*.pub)拷贝到服务端,然后通过以下命令添加到授权列表:
cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
这里假设公钥文件名称为 id_rsa.pub。
修改相关目录权限:
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
现在就可以在客户端通过 ssh 工具使用私钥连接服务端了。
文章评论