引言
最近经常在一台只有 1 Mbps 带宽的 Windows Server 2012 上改代码。RDP 连过去写几行代码就断一下连接,体验实在是非常的差,于是想能不能经由 VS Code Remote 获得好一点的体验。
搜了下资料,发现 Windows 10 1809 过后的版本自带了 OpenSSH Server 支持,可以很方便的搭建起 VS Code Remote 所需要的环境,但是早期一些的 OS 就没有官方的 Feature support。但好在自己折腾半天过后终于也给他整了起来,为了方便以后自己再踩坑,随记下本文。
至于为什么是 Windows 7 以上,因为官方是这么说的呀.jpg
(其实是因为 Windows 7 以后才有了 Powershell,而这个 Win32 的 OpenSSH 强依赖 Pwsh,所以这个方法最低只能支持到 Windows 7 啦)
操作步骤
下载微软官方的 OpenSSH
首先到 https://github.com/PowerShell/Win32-OpenSSH 找到合适自己系统版本的 OpenSSH,一般不是太老的其实用 Release 里最新 tag 的就可以。
这边以 x64 版本为例,下载 OpenSSH-Win64.zip
安装 sshd 服务
以管理员权限启动 Powershell,依次执行以下指令
# 切换到 OpenSSH 工作目录 cd 'C:\Program Files\OpenSSH' # 安装 sshd 服务 powershell.exe -ExecutionPolicy Bypass -File install-sshd.ps1 # 在防火墙中打开 22 端口 New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22 ## 如果以上指令无法执行,可以换成下面这条 netsh advfirewall firewall add rule name=sshd dir=in action=allow protocol=TCP localport=22 # 把 sshd 设置成开机自启动服务 Set-Service sshd -StartupType Automatic # 启动 sshd (如果此前在 %ProgramData%\ssh 下没有 host key 的话,这一步会在这个目录下创建 host key) net start sshd
(可选) 部署并启用公钥登录
文假设你已经生成过自己的客户端公钥,所以忽略公钥生成过程
部署公钥到远端服务器
对于普通权限账户
客户端的公钥 .ssh\id_rsa.pub
需要写入到远端服务器上 C:\Users\username\.ssh\
里一个叫 authorized_keys
的文本文件中。
下面的示例将利用 PowerShell 把客户端的公钥写入到服务器里(其中 username
替换为服务器对应的用户名,domain_name
换成对应的域(假如加了域的话))。第一次连接需要使用服务器的账户密码登录。
# 获取客户端机器上的公钥 $authorizedKey = Get-Content -Path $env:USERPROFILE\.ssh\id_rsa.pub # 生成将客户端公钥写入到远端服务器上的 authorized_keys 的脚本,并赋值到变量 $remotePowershell 上 $remotePowershell = "powershell New-Item -Force -ItemType Directory -Path $env:USERPROFILE\.ssh; Add-Content -Force -Path $env:USERPROFILE\.ssh\authorized_keys -Value '$authorizedKey'" # 连接到远端服务器并且执行变量 $remotePowerShell 对应的脚本 ssh username@domain_name@example.com $remotePowershell
对于具有管理员权限的账户
客户端的公钥 .ssh\id_rsa.pub
需要写入到远端服务器上 C:\ProgramData\ssh\
里一个叫 administrators_authorized_keys
的文本文件中。该文件的权限(Access Control List)需要配置为只允许 Administators 组和 System 访问。
下面的示例将利用 PowerShell 把客户端的公钥写入到服务器里并配置了 administrators_authorized_keys
的权限(其中 username
替换为服务器对应的用户名,domain_name
换成对应的域(假如加了域的话))。第一次连接需要使用服务器的账户密码登录。
# 获取客户端机器上的公钥 $authorizedKey = Get-Content -Path $env:USERPROFILE\.ssh\id_rsa.pub # 生成将客户端公钥写入到远端服务器上的 administrators_authorized_keys 的脚本,并赋值到变量$remotePowershell 上 $remotePowershell = "powershell Add-Content -Force -Path $env:ProgramData\ssh\administrators_authorized_keys -Value '$authorizedKey';icacls.exe ""$env:ProgramData\ssh\administrators_authorized_keys"" /inheritance:r /grant ""Administrators:F"" /grant ""SYSTEM:F""" # 连接到远端服务器并且执行变量 $remotePowerShell 对应的脚本 ssh username@domain_name@example.com $remotePowershell