sshd
Windows 自带可选的 OpenSSH,可以通过设置 - app - windows features - optional features (旧版Windows 10 在控制面板 control - windows feature里)或PowerShell安装。
PoserShell (run with administrator) 安装 sshd:
Get-WindowsCapability -Online | ? Name -like 'OpenSSH*'
# Install the OpenSSH Client
Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
# Install the OpenSSH Server
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
# Uninstall the OpenSSH Client
Remove-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
# Uninstall the OpenSSH Server
Remove-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
Start-Service sshd
# OPTIONAL but recommended:
Set-Service -Name sshd -StartupType 'Automatic'
# Confirm the Firewall rule is configured. It should be created automatically by setup.
Get-NetFirewallRule -Name *ssh*
# There should be a firewall rule named "OpenSSH-Server-In-TCP", which should be enabled
# If the firewall does not exist, create one
New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
The default shell used by Windows OpenSSH server is the Windows command shell.
注意:如果更改了 Windows 的 env 环境变量,似乎需要在 PowerShell 里重启 sshd 才能在连接 ssh 后的 shell 里反映出来。
Windows 10 的 OpenSSH shell 里各硬盘盘符会映射为 / 根目录下的文件夹,如 C 盘会映射为 "/C:" (注意有个冒号)目录。
ssh-copy-id
Windows 10 安装的 OpenSSH 自带 ssh-keygen, 但是没有 ssh-copy-id, 可以自己写个简单的 ssh-copy-id.bat 脚本模拟 ssh-copy-id 功能。
openssh-server
Windows 10 / 11 自带 OpenSSH server,但默认未启用,需要在 Settings - Optional features 里开启。启用后 services.msc 里会出现 "OpenSSH service" 和 "OpenSSH Authentication Agent" 这两个服务,但初始状态均为 "Manual",建议手工将其状态设为 "Automatic" 并启动之。Windows 自带的 openssh server 配置文件位置:
%PROGRAMDATA%/ssh/sshd_config
authorized_keys 文件位置:
- 非 administrators 组用户:%USERPROFILE%/.ssh/authorized_keys
- administrators 组用户:%PROGRAMDATA%/ssh/administrators_authorized_keys
注意这是因为傻逼微软在 sshd_config 里默认设置 administrators 用户使用单独的 authorized_keys 文件
Match Group administrators
AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys
authorized_keys 文件必须保证只允许 SYSTEM 和对应用户(以及administrators也可以?)可以访问,否则无法公钥登录。我测试时怎么修改 %PROGRAMDATA%/ssh/administrators_authorized_keys 的 NTFS 文件权限也无法以 administrators 登录,最后把 sshd_config 里配置"administrators_authorized_keys" 的那2行注释掉,直接使用标准位置的 authorized_keys 文件(%USERPROFILE%/.ssh/authorized_keys, 直接在资源管理器里创建文件,没有特别配置NTFS权限),一下子就搞定了,只能说傻逼微软!
注意 Linux 的 ssh-copy-id 无法正确上传公钥到 Windows 的 OpenSSH server 目录(因为路径与 Linux 不同),建议手工添加到 authorized_keys 里。
debug
先停止 sshd 服务,然后手动以 debug 模式开启 sshd 进程。
sc stop sshd
"C:\Windows\System32\OpenSSH\sshd.exe" -dd -E C:\sshd.log
Bug
测试 Windows 10 (LTSC 2019) 版的 OpenSSH 的 port forwarding 功能可能有 bug,怎么也无法转发成功。