一般配置到允许远程访问就可以使用了。
在 Ubuntu 上配置并启用 SSH 服务器,可以按照以下步骤操作:
1. 安装 SSH 服务器
Ubuntu 默认不安装 OpenSSH 服务器,所以首先需要安装它:
sudo apt update
sudo apt install -y openssh-server
2. 启动 SSH 服务
安装完成后,启用并启动 SSH 服务:
sudo systemctl enable ssh
sudo systemctl start ssh
检查 SSH 服务状态:
sudo systemctl status ssh
如果 SSH 运行正常,你会看到类似:
● ssh.service - OpenBSD Secure Shell server
Loaded: loaded (/lib/systemd/system/ssh.service; enabled; vendor preset: enabled)
Active: active (running)
3. 配置 SSH 允许远程访问
如果需要修改 SSH 配置,可以编辑 /etc/ssh/sshd_config
:
sudo nano /etc/ssh/sshd_config
确保以下选项正确:
PermitRootLogin no # 禁止 root 登录(建议)
PasswordAuthentication yes # 允许密码登录
PubkeyAuthentication yes # 允许密钥登录
如果做了修改,重启 SSH 服务:
sudo systemctl restart ssh
4. 允许防火墙放行 SSH(如果启用了 UFW 防火墙)
如果 Ubuntu 运行 UFW 防火墙,你需要放行 SSH 端口:
sudo ufw allow ssh
或者手动放行默认 SSH 端口 22:
sudo ufw allow 22/tcp
然后启用防火墙:
sudo ufw enable
检查规则是否生效:
sudo ufw status
5. 查找本机 SSH 服务器 IP
在局域网内,其他设备可以通过你的 Ubuntu 机器的 IP 访问 SSH 服务器:
ip a
一般情况下,eth0
或 wlan0
(有线/无线网络)下面的 inet
地址是你的 IP,例如:
inet 192.168.1.100/24
表示你的 SSH 服务器地址是 192.168.1.100
。
6. 在其他设备上连接 SSH
在 Windows(Git Bash/PowerShell)、Linux 或 Mac 终端上,使用以下命令连接 Ubuntu 服务器:
ssh username@192.168.1.100
(将 username
替换为你的 Ubuntu 用户名,192.168.1.100
替换为你的 Ubuntu IP)
如果使用 默认 22 端口,直接连接:
ssh username@192.168.1.100
如果你在 SSH 配置中修改了端口,例如 2222
,则需要:
ssh -p 2222 username@192.168.1.100
7. (可选)启用 SSH 公钥认证
如果你不想使用密码登录,可以配置 SSH 公钥认证:
7.1 在客户端生成 SSH 密钥
在你的客户端(比如 Windows 或其他 Linux 设备)运行:
ssh-keygen -t rsa -b 4096
然后,将公钥复制到 Ubuntu 服务器:
ssh-copy-id username@192.168.1.100
或者手动复制:
cat ~/.ssh/id_rsa.pub | ssh username@192.168.1.100 "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
之后,你就可以使用 SSH 免密码登录了:
ssh username@192.168.1.100
总结
操作 | 命令 |
---|---|
安装 SSH 服务器 | sudo apt install -y openssh-server |
启动 SSH 服务 | sudo systemctl start ssh |
设置 SSH 开机启动 | sudo systemctl enable ssh |
检查 SSH 运行状态 | sudo systemctl status ssh |
查看本机 IP | ip a |
允许防火墙放行 SSH | sudo ufw allow ssh |
重启 SSH 服务 | sudo systemctl restart ssh |
连接 SSH 服务器 | ssh username@192.168.1.100 |
这样,你的 Ubuntu 机器就可以作为 SSH 服务器使用了!🚀