笔记本电脑的内存用起来捉襟见肘,为了方便远程登录 Windows PC 上的 WSL 2 环境进行开发,需要开启 Windows 的 OpenSSH 服务端功能。整个链路结构如下:
---
config:
theme: 'base'
themeVariables:
darkMode: true
fontSize: 16px
primaryColor: '#000'
primaryTextColor: '#fff'
primaryBorderColor: '#02d7f2'
lineColor: '#fcee09'
tertiaryColor: '#0d0d0d'
tertiaryBorderColor: '#cdcdcd'
---
flowchart LR
subgraph Tailscale
direction LR
A
B
subgraph PC
direction LR
B
C
end
end
A["Laptop"] e1@--SSH--> B["Windows"]
B e2@-- 本地进程通信 --> C["WSL2"]
e1@{ animate: true }
e2@{ animate: true }
> if (!(Get-NetFirewallRule-Name"OpenSSH-Server-In-TCP"-ErrorAction SilentlyContinue)) { Write-Output"Firewall Rule 'OpenSSH-Server-In-TCP' does not exist, creating it..." New-NetFirewallRule-Name'OpenSSH-Server-In-TCP'-DisplayName'OpenSSH Server (sshd)'-Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort22 } else { Write-Output"Firewall rule 'OpenSSH-Server-In-TCP' has been created and exists." } # 正常情况下会显示防火墙规则已存在 Firewall rule 'OpenSSH-Server-In-TCP' has been created and exists.
配置免密登录
由于开启 OpenSSH 服务的 PC 是我的个人电脑,没有为管理员用户 thinklong 设置密码,但 SSH 登录时仍被要求输入密码,如果直接回车会被拒绝:
# 尝试SSH登录 > ssh thinklong@localhost The authenticity of host 'localhost (::1)' can't be established. ED25519 key fingerprint is SHA256:c+JdPZlkDWQ1gfd+0PM1eN7Pf123GydtvYe45qCV6j7. This key is not known by any other names. Are you sure you want to continue connecting (yes/no/[fingerprint])? yes Warning: Permanently added 'localhost' (ED25519) to the list of known hosts. thinklong@localhost's password: Permission denied, please try again.
熟悉 OpenSSH 服务端配置的话会知道 sshd_config 中有一个配置项 PermitEmptyPasswords 控制着是否允许无密码登录,但 Windows 上的情况要更复杂一点,需要无密码登录的可以展开查看——
Windows查看如何配置SSH无密码登录
OpenSSH 服务端配置文件中有两个选项与密码登录有关:
C:\ProgramData\ssh\sshd_config
# To disable tunneled clear text passwords, change to no here! PasswordAuthentication yes PermitEmptyPasswords yes
我们可以把这两个配置项都设为 yes,重启 sshd 服务后再次尝试登录,发现仍然要求输入密码,这就是 Windows 上特殊的地方。
在 Linux 上 sshd 会自己查 /etc/shadow,如果密码是空的就能成功。但在 Windows 上 OpenSSH 不自己做验证,而是调用 Windows 的登录 API,并且在 Windows 本地安全策略中有一条“账户:使用空密码的本地账户只允许进行控制台登录”,默认为启用,需要将这条策略改为禁用才能允许空密码登录。
# To disable tunneled clear text passwords, change to no here! - #PasswordAuthentication yes + PasswordAuthentication no - #PermitEmptyPasswords no + PermitEmptyPasswords no
此外,还注意到 sshd_config 文件存在如下配置:
C:\ProgramData\ssh\sshd_config
# The default is to check both .ssh/authorized_keys and .ssh/authorized_keys2 # but this is overridden so installations will only check .ssh/authorized_keys AuthorizedKeysFile .ssh/authorized_keys
Match Group administrators AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys