使用 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 有兩個端口號,你可以用 winrm get winrm/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 的權限,把用戶加入到 Remote Desktop Users
這個用戶組中就會有Remote 的權限
Reference
- https://www.faqforge.com/windows/create-powershell-session-remote-computer/
- https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_remote_troubleshooting?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