Ubuntu 24.02 LTS 系统远程开发

Ubuntu 服务器端安装 SSH, 客户端通过 Xshell, vscode 远程连接

Ubuntu SSH-server

确认 Ubuntu 是否安装 SSH, Ubuntu 自带客户端

1
2
3
$ dpkg -l | grep ssh
ii libssh-4:amd64 0.10.6-2build2 amd64 tiny C SSH library (OpenSSL flavor)
ii openssh-client 1:9.6p1-3ubuntu13.5 amd64 secure shell (SSH) client, for secure access to remote machines

安装服务器

1
2
sudo apt update
sudo apt install openssh-server

检查 SSH 服务是否正在运行, 并启动

1
2
3
sudo systemctl status ssh
sudo systemctl start ssh
sudo systemctl enable ssh

另一种方法

1
2
$ ps -e | grep ssh
590323 ? 00:00:00 sshd

查看 ip 地址 ifconfig

Xshell

首先在 Ubuntu 系统上创建新用户

1
2
3
4
5
sudo adduser xxx
sudo passwd xxx
sudo groupadd SSHD_USER
sudo usermod -G SSHD_USER xxx
cat /etc/group | grep SSHD_USER

sshd_config 中仅允许连接 SSHD_USER 组

1
2
3
AllowGroups SSHD_USER
Match Group SSHD_USER
PasswordAuthentication yes

检查设置是否正确并重启

1
2
3
4
$ sudo sshd -t
$ sudo systemctl restart sshd
$ sudo systemctl status sshd
Active: active (running) since Thu 2024-10-31 16:44:49 CST; 4s ago

检查用户是否可登录

1
ssh xxx@xxx.xxx.xx.xxx

在 Windows 客户端上安装 xshell 并连接

  1. 下载个人版 xshell & xftp (https://www.xshell.com/zh/free-for-home-school/) 并安装
  2. 新建会话,设置连接名、协议(SSH)、主机ip、端口号
  3. 用户身份验证 通过 SSH 公钥连接
  4. 首次连接时获得公钥与私钥,选择 接受并保存
  5. 点击连接, 输入用户名 “xxx” 和密码

VSCode

  1. VSCode 安装 Remote - SSH
  2. 连接到主机 Connect to Host...
  3. 添加新的主机 Add New SSH Host...
  4. 输入地址 ssh HostName@xxx.xxx.xx.xxx:22
  5. 选择更新本地的 SSH 配置文件 C:\Users\xxx\.ssh\config
  6. 设置好后连接输入账号密码
  7. 出错注意提前设置 Remote - SSH 插件中 Config FileRemote.SSH: Path 选项,同时确保本地与服务器 vscode 版本一致

vscode remote-ssh 连接失败的基本原理

SSH protection

  1. 检查配置文件启用选项,备份 SSH 配置文件
1
2
sudo sshd –T
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
  1. 打开文件
1
sudo vim /etc/ssh/sshd_config
  1. 禁用基于密码的身份验证和空密码
1
2
PasswordAuthentication no
PermitEmptyPasswords no
  1. 禁用 root 登陆
1
PermitRootLogin no
  1. 使用 SSH 协议 2,现代的 OpenSSH 版本通常默认只支持协议2,因此不需要显式指定
1
Protocol 2
  1. 设置会话超时
1
ClientAliveInterval 300
  1. 允许特定用户访问 SSH 服务器并限制身份尝试次数
1
2
AllowUsers xxx
MaxAuthTries 3
  1. 检查设置是否正确
1
sudo sshd -t
  1. 重新加载 SSH 服务器
1
sudo service sshd reload

reference

CSDN-Ubuntu18.04服务器远程连接指南
如何保护 Ubuntu 20.04 中的 SSH 服务器
华为云-VSCode远程连接Ubuntu/Linux
知乎-在 Linux 上保护 SSH 服务器连接的 8 种方法
CSDN-Linux创建用户并授予SSH权限

0%