安装SSH服务
在Ubuntu服务器上执行以下命令安装OpenSSH服务器:
sudo apt update
sudo apt install openssh-server
安装后服务会自动启动,可通过sudo systemctl status ssh查看状态。
配置SSH(可选)
/etc/ssh/sshd_config,找到Port 22改为其他端口(如2222),重启服务生效。PermitRootLogin设为no,增强安全性。PubkeyAuthentication yes,并配置authorized_keys文件。sudo systemctl restart ssh。配置防火墙(若启用)
若使用UFW防火墙,需放行SSH端口:
sudo ufw allow ssh # 或指定端口如 sudo ufw allow 2222/tcp
sudo ufw enable
在客户端终端输入:
ssh username@server_ip -p port
username:服务器上的用户名(如ubuntu)。server_ip:服务器IP地址(可通过ip a查看)。port:SSH端口(默认22,若修改需指定)。yes即可。ssh-keygen -t rsa -b 4096
按提示回车使用默认路径和密码(可选)。ssh-copy-id -i ~/.ssh/id_rsa.pub username@server_ip -p port
或手动将~/.ssh/id_rsa.pub内容追加到服务器~/.ssh/authorized_keys文件。ssh -i ~/.ssh/id_rsa username@server_ip -p port
(若私钥路径为默认,可省略-i参数)。sudo systemctl status ssh。sudo ufw status。/etc/ssh/sshd_config是否正确(如端口、密码认证等)。~/.ssh目录权限为700,authorized_keys文件权限为600。| 操作 | 命令 |
|---|---|
| 安装SSH服务 | sudo apt install openssh-server |
| 启动/重启SSH服务 | sudo systemctl start/stop/restart ssh |
| 查看SSH状态 | sudo systemctl status ssh |
| 生成密钥对 | ssh-keygen -t rsa -b 4096 |
| 复制公钥到服务器 | ssh-copy-id username@server_ip -p port |
| 连接SSH服务器 | ssh username@server_ip -p port |
参考来源: