通过SSH远程登录Windows Server

通过 SSH 密钥远程登录 Windows Server,通常需要先确保 Windows Server 上的 OpenSSH 服务器正确配置,并且客户端已经生成并配置好密钥。以下是完整的步骤:


1. 在客户端生成 SSH 密钥

如果你尚未生成 SSH 密钥,可以在 macOS 或 Linux 终端执行:

ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa

然后会生成两个文件:

​ • id_rsa(私钥)

​ • id_rsa.pub(公钥)

如果你使用 Windows,可以使用 PowerShell:

ssh-keygen -t rsa -b 4096 -f $env:USERPROFILE\.ssh\id_rsa

2. 在 Windows Server 上安装 OpenSSH

Windows Server 2019 及以上版本内置 OpenSSH,但需要手动启用。

步骤:

​ 1. 以管理员身份打开 PowerShell。

​ 2. 运行以下命令安装 OpenSSH 服务器:

Add-WindowsFeature -Name OpenSSH-Server

​ 3. 启动 SSH 服务:

Start-Service sshd

​ 4. 设置开机自启:

Set-Service -Name sshd -StartupType Automatic

3. 配置 SSH 服务器允许密钥登录

编辑 SSH 配置文件

​ 1. 进入 OpenSSH 配置目录:

notepad C:\ProgramData\ssh\sshd_config

​ 2. 确保以下参数被正确设置(去掉 # 注释):

PubkeyAuthentication yes
PasswordAuthentication no
AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys

​ 3. 保存文件并关闭。

添加公钥

​ 1. 将客户端的 id_rsa.pub 复制到 Windows 服务器:

mkdir C:\ProgramData\ssh
notepad C:\ProgramData\ssh\administrators_authorized_keys

​ 2. 在 administrators_authorized_keys 文件中粘贴 id_rsa.pub 的内容,然后保存。

设置权限

icacls C:\ProgramData\ssh\administrators_authorized_keys /inheritance:r
icacls C:\ProgramData\ssh\administrators_authorized_keys /grant SYSTEM:F
icacls C:\ProgramData\ssh\administrators_authorized_keys /grant Administrators:F

重启 SSH 服务

Restart-Service sshd

4. 远程连接 Windows Server

在客户端(Mac/Linux/Windows)上使用 SSH 进行连接:

ssh -i ~/.ssh/id_rsa Administrator@<Windows-Server-IP>

如果使用 Windows PowerShell:

ssh -i $env:USERPROFILE\.ssh\id_rsa Administrator@<Windows-Server-IP>

5.(可选)允许 Windows 防火墙开启 SSH 端口

如果连接失败,可能是 Windows 防火墙拦截了端口 22,可以执行:

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

这样,你就可以使用 SSH 密钥成功远程登录 Windows Server 了!

posted on 2025-03-08 10:48  朝朝暮Mu  阅读(326)  评论(0)    收藏  举报