随机
Enter 搜索 ↑↓ 切换 Esc 清空

win-openssh

脚本

Windows 开启 OpenSSH Server 服务(默认 Shell 改为 PowerShell)

补充说明

Windows 10 1809+、Windows 11 及 Windows Server 2019 及以上系统自带 OpenSSH Server 组件,无需额外下载安装包。全程使用管理员 PowerShell 执行,安装完成后即可通过 ssh 命令远程连接 Windows 主机,默认登录进入 cmd,可通过注册表将默认 Shell 改为 PowerShell。

适用场景:低带宽、脚本批量运维、Ansible 自动化等不适合使用 RDP 的场景。

前置准备:确认环境

条件 说明
操作系统 Windows 10 1809+ / Windows 11 / Windows Server 2019 及以上
权限 以管理员身份运行 PowerShell
网络 目标 Windows 主机可访问,TCP 22 端口可放行

核心步骤一:查看 OpenSSH Server 状态

Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH.Server*'

输出示例:

Name  : OpenSSH.Server~~~~0.0.1.0
State : NotPresent

NotPresent 代表未安装;如果是 Installed 表示已经安装好。

核心步骤二:安装 OpenSSH Server

Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0

输出示例:

Path          :
Online        : True
RestartNeeded : False

✅ 无需重启系统。

核心步骤三:启动 sshd 服务并设置开机自启

Start-Service sshd
Set-Service -Name sshd -StartupType Automatic

检查服务状态:

Get-Service sshd

成功输出:

Status   Name               DisplayName
------   ----               -----------
Running  sshd               OpenSSH SSH Server

安装 OpenSSH Server 时会自动在防火墙放行 22 端口的入站规则 OpenSSH-Server-In-TCP;如连接超时,可手动放行 TCP 22 端口:

New-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22

核心步骤四:修改注册表将默认 Shell 改为 PowerShell

默认 SSH 登录 Windows 后进入 cmd,通过注册表 DefaultShell 指定为 powershell.exe:

# 先创建注册表项(不存在则新建,存在也不会报错)
New-Item -Path 'HKLM:\SOFTWARE\OpenSSH' -Force

# 设置 DefaultShell 字符串值
New-ItemProperty -Path 'HKLM:\SOFTWARE\OpenSSH' -Name DefaultShell `
-Value 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe' `
-PropertyType String -Force

返回结果:

DefaultShell : C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
PSPath       : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\OpenSSH

如需使用 PowerShell 7(pwsh),只需将 Value 替换为 pwsh 完整路径即可。

核心步骤五:重启 sshd 服务,让 Shell 配置生效

Restart-Service sshd

核心步骤六:远程 SSH 测试连接

在另一台机器(Linux、Mac、Windows 均可)执行:

ssh 用户名@WindowsIP

用户名为 Windows 本地账号或域账号,输入账号密码后,登录成功直接进入 PowerShell,不再是 CMD。

故障排查与避坑指南

现象 可能原因 解决方案
Get-WindowsCapability 返回 NotPresent OpenSSH Server 未安装 执行 Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0 安装
sshd 服务未启动 服务未启动或未设置自启 执行 Start-Service sshd 和 Set-Service -Name sshd -StartupType Automatic
SSH 连接超时 防火墙未放行 TCP 22 端口 手动添加 OpenSSH-Server-In-TCP 入站规则
登录后进入 cmd 而非 PowerShell 注册表 DefaultShell 未配置 设置 HKLM:\SOFTWARE\OpenSSH\DefaultShell 为 powershell.exe 路径并重启 sshd

关键避坑要点

  • 全程需以管理员身份运行 PowerShell,否则安装服务和修改注册表会失败。
  • 安装完成后无需重启系统,但修改注册表后需重启 sshd 服务才能生效。
  • 默认登录进入 cmd,如需进入 PowerShell 必须配置注册表 DefaultShell。
  • TCP 22 端口若被第三方防火墙拦截,需额外放行。

参考资料

适用版本:Windows 10 1809+ / Windows 11 / Windows Server 2019 及以上

目录