Ubuntu中SSH服务器安装使用
SSH服务安装
1. 安装 OpenSSH
安装 SSH 服务端(允许远程登录)
sudo apt update
sudo apt install openssh-server
安装 SSH 客户端(用于连接其他服务器)
sudo apt install openssh-client
2. 检查 SSH 服务状态
sudo systemctl status ssh
-
如果未运行,启动 SSH:
sudo systemctl start ssh
-
设置开机自启:
sudo systemctl enable ssh
3. 配置 SSH(可选)
默认配置文件位于 /etc/ssh/sshd_config
,可修改以提高安全性:
sudo nano /etc/ssh/sshd_config
常见优化选项
Port 2222 # 更改默认端口(22 → 2222,防止扫描)
PermitRootLogin no # 禁止 root 远程登录
PasswordAuthentication no # 禁用密码登录(仅密钥登录更安全)
AllowUsers aixi # 只允许特定用户登录
应用更改
sudo systemctl restart ssh
4. 允许 SSH 通过防火墙
如果启用了 ufw
,需放行 SSH:
sudo ufw allow 22 # 如果使用默认端口 22
sudo ufw allow 2222 # 如果修改了端口(如 2222)
sudo ufw enable # 启用防火墙
sudo ufw status # 查看规则
5. 远程连接 SSH
从 Linux/Mac 连接
ssh username@server_ip -p 22
username
:你的 Ubuntu 用户名server_ip
:服务器 IP 地址(用ip a
或hostname -I
查看)-p 22
:如果修改了端口(如2222
),需指定
从 Windows 连接
使用 PuTTY 或 Windows Terminal,输入服务器 IP 和端口。
6. 卸载 OpenSSH
移除 SSH 服务端
sudo apt remove --purge openssh-server
移除 SSH 客户端
sudo apt remove --purge openssh-client
清理配置
sudo apt autoremove
常见问题
1. “Connection refused” 错误
- 检查 SSH 是否运行:
sudo systemctl status ssh
- 检查防火墙是否放行端口:
sudo ufw status
2. 忘记 SSH 端口
查看当前配置:
sudo grep Port /etc/ssh/sshd_config
3. 密钥登录(更安全)
生成密钥对:
ssh-keygen -t ed25519
将公钥上传到服务器:
ssh-copy-id -i ~/.ssh/id_ed25519.pub username@server_ip