使用SSH管理Windows

  1. 1. 安装OpenSSH Server
    1. 1.1. 图形界面
    2. 1.2. PowerShell方式
      1. 1.2.1. 确认OpenSSH可用于安装
      2. 1.2.2. 安装OpenSSH Server
  2. 2. OpenSSH Server 服务配置
    1. 2.1. 服务、防火墙相关
    2. 2.2. 配置密钥免密登录
    3. 2.3. (可选)配置PowerShell作为SSH连接默认SHELL
  3. 3. 参考链接

网上有很多关于使用win10-ssh客户端登录linux-ssh服务端的介绍,但很少介绍多台win10-ssh服务端之间互访的。以下记录如何免密登录win10-ssh服务

  • 根据微软文档描述,适用于Windows 10 1809 或 Windows Server 2019以上版本
  • 以下内容如果无特别说明,在远程Windows主机上操作

安装OpenSSH Server

图形界面

点开 设置 -> 应用 -> 应用与功能 -> 可选功能

点击 添加功能 后跳出对话框,输入”ssh”,勾选安装”OpenSSH 服务器”

PowerShell方式

以下操作需要管理员权限

确认OpenSSH可用于安装

1
Get-WindowsCapability -Online | ? Name -like 'OpenSSH*'

输出以下内容

1
2
3
4
5
Name  : OpenSSH.Client~~~~0.0.1.0
State : Installed

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

安装OpenSSH Server

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

输出以下内容

1
2
3
Path          :
Online : True
RestartNeeded : False

OpenSSH Server 服务配置

以下操作需要管理员权限

服务、防火墙相关

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 开启服务
Start-Service sshd

# 设置自启动
Set-Service -Name sshd -StartupType 'Automatic'

# 查看状态
Get-Service sshd

#关闭服务
Stop-Service sshd

# 重启服务
Restart-Service sshd

# 确认防火墙是放开的
Get-NetFirewallRule -Name *ssh*
  1. 确认OpenSSH-Server-In-TCP状态是 enabled
  2. 至此可以在本地尝试ssh username@ip连接到远程机器

配置密钥免密登录

↓本地执行

1
2
3
4
5
6
7
8
# 生成密钥对
ssh-keygen -t rsa

# 找到公钥文件,复制内容备用
# Windows
# %HOMEPATH%\.ssh\id_rsa.pub
# Linux
# $HOME/.ssh/id_rsa.pu

↑本地执行 | 远程执行↓

  1. 打开文件%HOMEPATH%\.ssh\authorized_keys
  2. 把公钥文件添加到上述文件末尾
  3. 修改文件C:\ProgramData\ssh\sshd_config,内容如下
  4. 重启服务Restart-Service sshd
1
2
3
4
5
6
7
8
C:\ProgramData\ssh\sshd_config
确保以下3条没有被注释
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys

确保以下2条有注释掉
# Match Group administrators
# AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys

(可选)配置PowerShell作为SSH连接默认SHELL

1
2
3
# 管理员运行
New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -PropertyType String -Force
Restart-Service sshd

参考链接

适用于 Windows 10 1809 和 Server 2019 的 OpenSSH 服务器配置