使用 Powershell 远程连接 windows server
Intro
最近我们的开发环境增加了一个 windows 服务器,没有界面的,不能直接远程桌面连上去管理,需要使用 Powershell 管理,于是就有了这篇文章的探索。
windows服务器配置
以下所有命令需要在管理员账户下执行,请以管理员身份运行下面的命令。
- 在远程 windows服务器上启用 powershell 远程会话: 
- Enable-PSRemoting -Force
- 配置 TrustedHosts 
- winrm set winrm/config/client '@{TrustedHosts="<your local ip>"}'
- # winrm set winrm/config/client '@{TrustedHosts="58.123.45.26,134.86.23.21"}' #多个地址用英文的逗号分隔
配置好之后需要重启一下服务:
- Restart-Service WinRM
- 防火墙开放 5985 端口 
winrm 有两个端口号,你可以用 winrmgetwinrm/config/client 命令来查看 winrm client 相关配置信息,

可以看到默认的两个端口
- http:5985
- https:5986
我们只用了 http 所以开放 5985 端口
本地配置
- 配置 TrustedHosts 
- winrm set winrm/config/client '@{TrustedHosts="<remote server ip or host>"}'
- # winrm set winrm/config/client '@{TrustedHosts="58.123.45.26,134.86.23.21"}' #多个地址用英文的逗号分隔
- 连接远程服务器 
- Enter-PSSession -ComputerName <remoteIp or host> -Credential <username>
连接之后,会提示输入对应用户的密码,提交之后就会进行身份验证
出现如下图所示的提示就说明连接成功了,在执行命令就相当于是在远程windows服务器上执行命令了,就相当于是 SSH 到了 linux 服务器上了

疑难解答
- ACCESS IS DENIED
如果你的用户名密码都是正确的,但是还是一直提示 ACCESS IS DENIED,那么你需要检查一下这个用户是否有 Remote 的权限,远程的用户至少要有 Remote 的权限,把用户加入到 RemoteDesktopUsers 这个用户组中就会有Remote 的权限
更多问题请参考: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/aboutremotetroubleshooting?view=powershell-6
Reference
- https://www.faqforge.com/windows/create-powershell-session-remote-computer/ 
- https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/aboutremotetroubleshooting?view=powershell-6 
- https://docs.microsoft.com/en-us/windows-server/administration/server-manager/server-manager 
- https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/enter-pssession?view=powershell-6 
- https://www.itprotoday.com/windows-78/how-remotely-manage-windows-server-2016