远程管理Windows - 命令行以及图形界面
Windows远程管理简述
Windows远程管理方式
- GUI:通过【远程桌面】来远程登录
- 前提
- 启用远程桌面
- 用户有远程登录权限(加入组Administrators,或者“Remote Desktop Users”。可以自定义,见附录)
- 客户端
- 远程桌面连接:MSTSC
- mobaxterm等支持RDP协议的客户端
- 前提
- CLI:通过WinRM(Powershell)来远程登录
- 前提
- 配置并启用WinRM
- 用户有远程登录权限(加入组Administrators,或者“Remote Desktop Users”)
- 客户端
- Powershell(WinRM属于内置模块 / 命令来的?)
- 前提
温馨提示
- Windows 10 Home Edition不支持远程桌面
- Windows 10和Windows Server的远程桌面设置是共通的
远程桌面GUI
启用远程桌面GUI
按Win+I,进入【系统】 - 【远程桌面】 - 启用远程桌面
登录远程桌面GUI
通过各种RDP客户端登录。(略)
远程管理CLI(WinRM)
资料及命令总结
微软文档WinRM
https://docs.microsoft.com/ja-jp/windows/win32/winrm/installation-and-configuration-for-windows-remote-management
微软文档远程命令管理
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/enter-pssession?view=powershell-7.2
Ansible批量管理Windows的文档
https://docs.ansible.com/ansible/2.9_ja/user_guide/windows_winrm.html
命令一览,命令参考
## 设置WinRM
winrm quickconfig
# 查看当前WinRM配置
winrm e winrm/config/listener
winrm get winrm/config
## 远程登录命令
# Enter-PSSession交互式远程登录
Enter-PSSession -ComputerName WS2019EN -Credential localhost\administrator
# 退出
Exit-PSSession
## 非交互式远程执行命令or脚本
# 首先获取登录用户资格
$admin=Get-Credential -Credential localhost\administrator
# 获取主机列表,-ComputerName后可以跟多个主机,逗号隔开
$hostlist=$(New-PSSession -ComputerName WS2019EN -Credential $admin)
# 执行命令
Invoke-Command -Session $hostlist -ScriptBlock { Get-LocalGroupMember administrators | Select-Object PSComputerName,Name }
# 执行脚本
Invoke-Command -Session $hostlist -FilePath "C:\scripts\test.ps1"
# ps脚本执行策略
Set-ExecutionPolicy Unrestricted
Get-ExecutionPolicy
## 修改网络配置文件
# 查看当前配置
Get-NetConnectionProfile
# 修改为Private
Set-NetConnectionProfile -Name "Unidentified network" -NetworkCategory Private
## 设置TrustedHost
# 添加信任主机TrustedHost,可一次加多个,逗号隔开。每次执行都是删除以前的设置来的。。。
Set-Item WSMan:\localhost\Client\TrustedHosts -Value host1,host2...
# 查看
Get-Item WSMan:\localhost\Client\TrustedHosts
# 删除所有信任主机
Clear-Item WSMan:\localhost\Client\Trustedhosts
Set-Item WSMan:\localhost\Client\TrustedHosts -Value ""
配置并启用远程管理WinRM
# 快速配置
PS C:\Users\Administrator> winrm quickconfig
WinRM service is already running on this machine.
WinRM is not set up to allow remote access to this machine for management.
The following changes must be made:
Configure LocalAccountTokenFilterPolicy to grant administrative rights remotely to local users.
Make these changes [y/n]? y
WinRM has been updated for remote management.
Configured LocalAccountTokenFilterPolicy to grant administrative rights remotely to local users.
PS C:\Users\Administrator>
# 查看当前监听的端口等信息
PS C:\Users\Administrator> winrm e winrm/config/listener
Listener
Address = *
Transport = HTTP
Port = 5985
Hostname
Enabled = true
URLPrefix = wsman
CertificateThumbprint
ListeningOn = 127.0.0.1, 192.168.50.12, ::1, fe80::a017:805f:e015:2531%9
# 获取配置
PS C:\Users\Administrator> winrm get winrm/config
Config
MaxEnvelopeSizekb = 500
MaxTimeoutms = 60000
MaxBatchItems = 32000
MaxProviderRequests = 4294967295
Client
NetworkDelayms = 5000
URLPrefix = wsman
AllowUnencrypted = false
Auth
Basic = true
Digest = true
Kerberos = true
Negotiate = true
Certificate = true
CredSSP = false
DefaultPorts
HTTP = 5985
HTTPS = 5986
TrustedHosts
Service
RootSDDL = O:NSG:BAD:P(A;;GA;;;BA)(A;;GR;;;IU)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;;WD)
MaxConcurrentOperations = 4294967295
MaxConcurrentOperationsPerUser = 1500
EnumerationTimeoutms = 240000
MaxConnections = 300
MaxPacketRetrievalTimeSeconds = 120
AllowUnencrypted = false
Auth
Basic = false
Kerberos = true
Negotiate = true
Certificate = false
CredSSP = false
CbtHardeningLevel = Relaxed
DefaultPorts
HTTP = 5985
HTTPS = 5986
IPv4Filter = *
IPv6Filter = *
EnableCompatibilityHttpListener = false
EnableCompatibilityHttpsListener = false
CertificateThumbprint
AllowRemoteAccess = true
Winrs
AllowRemoteShellAccess = true
IdleTimeout = 7200000
MaxConcurrentUsers = 2147483647
MaxShellRunTime = 2147483647
MaxProcessesPerShell = 2147483647
MaxMemoryPerShellMB = 2147483647
MaxShellsPerUser = 2147483647
配置的时候如果报错,警告网络连接是pubilc的情况
PS C:\Windows\system32> winrm quickconfig
WinRM is not set up to receive requests on this machine.
The following changes must be made:
Start the WinRM service.
Set the WinRM service type to delayed auto start.
Make these changes [y/n]? y
WinRM has been updated to receive requests.
WinRM service type changed successfully.
WinRM service started.
WSManFault
Message
ProviderFault
WSManFault
Message = WinRM firewall exception will not work since one of the network connection types on this machine is set to Public. Change the network connection type to either Domain or Private and try again.
Error number: -2144108183 0x80338169
WinRM firewall exception will not work since one of the network connection types on this machine is set to Public. Change the network connection type to either Domain or Private and try again.
# 获取当前设置
PS C:\Windows\system32> Get-NetConnectionProfile
Name : Unidentified network
InterfaceAlias : Ethernet 2
InterfaceIndex : 14
NetworkCategory : Public
IPv4Connectivity : NoTraffic
IPv6Connectivity : NoTraffic
# 修改为Private之后再次查看,设置WinRM
PS C:\Windows\system32> Set-NetConnectionProfile -Name "Unidentified network" -NetworkCategory Private
PS C:\Windows\system32> Get-NetConnectionProfile
Name : Unidentified network
InterfaceAlias : Ethernet 2
InterfaceIndex : 14
NetworkCategory : Private
IPv4Connectivity : NoTraffic
IPv6Connectivity : NoTraffic
PS C:\Windows\system32> winrm quickconfig
WinRM service is already running on this machine.
WinRM is not set up to allow remote access to this machine for management.
The following changes must be made:
Enable the WinRM firewall exception.
Configure LocalAccountTokenFilterPolicy to grant administrative rights remotely to local users.
Make these changes [y/n]? y
WinRM has been updated for remote management.
WinRM firewall exception enabled.
Configured LocalAccountTokenFilterPolicy to grant administrative rights remotely to local users.
PS C:\Windows\system32>
网络设置参考
https://cn.univdesigntechnologies.com/how-change-windows-10-network-location-private
远程登录CLI
对于没有加入域的计算机直接远程登录会报错(比如直接在VMware workstation,或者VIrtualBox上直接建立虚拟机)
PS C:\Windows\system32> Enter-PSSession -ComputerName 192.168.50.12 -Credential localhost\administrator
Enter-PSSession : Connecting to remote server 192.168.50.12 failed with the following error message :
The WinRM client cannot process the request. If the authentication scheme is different from Kerberos,
or if the client computer is not joined to a domain, then HTTPS transport must be used or the
destination machine must be added to the TrustedHosts configuration setting. Use winrm.cmd to
configure TrustedHosts. Note that computers in the TrustedHosts list might not be authenticated. You
can get more information about that by running the following command: winrm help config. For more
information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ Enter-PSSession -ComputerName 192.168.50.12 -Credential localhost\adm ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (192.168.50.12:String) [Enter-PSSession], PSRemotingTr
ansportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed
# 中文版
PS C:\> Enter-PSSession -ComputerName 192.168.50.12 -Credential localhost\administrators
Enter-PSSession : 连接到远程服务器 192.168.50.12 失败,并显示以下错误消息: WinRM 客户端无法处理该请求。如果身份验证方案与 Kerberos 不同,或者客户端计算
机未加入到域中, 则必须使用 HTTPS 传输或者必须将目标计算机添加到 TrustedHosts 配置设置。 使用 winrm.cmd 配置 TrustedHosts。请注意,TrustedHosts 列表中的
计算机可能未经过身份验证。 通过运行以下命令可获得有关此内容的更多信息: winrm help config。 有关详细信息,请参阅 about_Remote_Troubleshooting 帮助主题。
所在位置 行:1 字符: 1
+ Enter-PSSession -ComputerName 192.168.50.12 -Credential localhost\adm ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (192.168.50.12:String) [Enter-PSSession],PSRemotingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed
解决方法:
- 加入域【暂略】
- 使用https【暂略】
- 添加到Trustedhosts
添加到Trustedhosts的做法
# 参考
# https://www.ipentec.com/document/windows-windows-10-add-winrm-trasted-hosts
# 添加信任主机
PS C:\Windows\system32> Set-Item WSMan:\localhost\Client\TrustedHosts -Value WS2019EN
WinRM Security Configuration.
This command modifies the TrustedHosts list for the WinRM client. The computers in the TrustedHosts
list might not be authenticated. The client might send credential information to these computers. Are
you sure that you want to modify this list?
[Y] Yes [N] No [S] Suspend [?] Help (default is "Y"): y
PS C:\Windows\system32>
# 确认配置
PS C:\Windows\system32> Get-Item WSMan:\localhost\Client\TrustedHosts
WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Client
Type Name SourceOfValue Value
---- ---- ------------- -----
System.String TrustedHosts WS2019EN
# 再次执行远程登录,由于用主机名配置了信任主机,所以连接的时候得用主机名。或者再添加信任ip
PS C:\Windows\system32> Enter-PSSession -ComputerName 192.168.50.12 -Credential localhost\administrator
Enter-PSSession : Connecting to remote server 192.168.50.12 failed with the following error message :
The WinRM client cannot process the request. If the authentication scheme is different from Kerberos,
or if the client computer is not joined to a domain, then HTTPS transport must be used or the
destination machine must be added to the TrustedHosts configuration setting. Use winrm.cmd to
configure TrustedHosts. Note that computers in the TrustedHosts list might not be authenticated. You
can get more information about that by running the following command: winrm help config. For more
information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ Enter-PSSession -ComputerName 192.168.50.12 -Credential localhost\adm ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (192.168.50.12:String) [Enter-PSSession], PSRemotingTr
ansportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed
# 执行Enter-PSSession命令后,-Credential选项出弹出一个交互式窗口输入命令。默认远程主机的主机名会显示在命令行的开头
PS C:\Windows\system32> Enter-PSSession -ComputerName WS2019EN -Credential localhost\administrator
[WS2019EN]: PS C:\Users\Administrator\Documents>
# 执行cmd命令查看主机名
[WS2019EN]: PS C:\Users\Administrator\Documents> hostname
WS2019EN
# 执行powershell命令查看本地用户组成员等
[WS2019EN]: PS C:\Users\Administrator\Documents> Get-LocalGroupMember administrators
ObjectClass Name PrincipalSource
----------- ---- ---------------
User WS2019EN\Administrator Local
# 在WinRM里好像无法打开新的交互式窗口
[WS2019EN]: PS C:\Users\Administrator\Documents> diskpart
Microsoft DiskPart version 10.0.17763.1
Copyright (C) Microsoft Corporation.
On computer: WS2019EN
DISKPART>
[WS2019EN]: PS C:\Users\Administrator\Documents>
交互式窗口输入命令
非交互式远程执行命令
# 获取用户资格
PS C:\Windows\system32> Get-Credential -Credential localhost\administrator
UserName Password
-------- --------
localhost\administrator System.Security.SecureString
# 获取用户资格并保存到变量admin
PS C:\Windows\system32> $admin=Get-Credential -Credential localhost\administrator
# 查看用户资格
PS C:\Windows\system32> $admin
UserName Password
-------- --------
localhost\administrator System.Security.SecureString
# 获取远程主机列表
PS C:\Windows\system32> $host=$(New-PSSession -ComputerName WS2019EN -Credential $admin)
Cannot overwrite variable Host because it is read-only or constant. # host是个内置只读变量。。。
At line:1 char:1
+ $host=$(New-PSSession -ComputerName WS2019EN -Credential $admin)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (Host:String) [], SessionStateUnauthorizedAccessException
+ FullyQualifiedErrorId : VariableNotWritable
PS C:\Windows\system32> $hostlist=$(New-PSSession -ComputerName WS2019EN -Credential $admin)
PS C:\Windows\system32> $hostlist
Id Name ComputerName ComputerType State ConfigurationName Availability
-- ---- ------------ ------------ ----- ----------------- ------------
5 WinRM5 WS2019EN RemoteMachine Opened Microsoft.PowerShell Available
# 远程执行命令
PS C:\Windows\system32> Invoke-Command -Session $hostlist -ScriptBlock { Get-LocalGroupMember administrators }
PSComputerName : WS2019EN
RunspaceId : 27cf2a8b-8faa-4062-9b2b-e84aa580f6a9
Name : WS2019EN\Administrator
SID : S-1-5-21-2777051605-775209863-3905695340-500
PrincipalSource : Local
ObjectClass : User
# 远程执行命令,+整型
PS C:\Windows\system32> Invoke-Command -Session $hostlist -ScriptBlock { Get-LocalGroupMember administrators | Select-Object PSComputerName,Name }
Name PSComputerName RunspaceId
---- -------------- ----------
WS2019EN\Administrator WS2019EN 27cf2a8b-8faa-4062-9b2b-e84aa580f6a9
# 远程执行脚本(脚本存在本机)
PS C:\Windows\system32> type "C:\scripts\test.ps1"
Get-Process winlogon
PS C:\Windows\system32> Invoke-Command -Session $hostlist -FilePath "C:\scripts\test.ps1"
Invoke-Command : File C:\scripts\test.ps1 cannot be loaded because running scripts is disabled on this system. For more
information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ Invoke-Command -Session $hostlist -FilePath "C:\scripts\test.ps1"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : SecurityError: (:) [Invoke-Command], PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess,Microsoft.PowerShell.Commands.InvokeCommandCommand
PS C:\Windows\system32>
# 修改脚本执行策略后(本地主机,方便起见这里设置为无限制),远程执行脚本(脚本存在本机)
PS C:\Users\Administrator> Set-ExecutionPolicy Unrestricted
Execution Policy Change
The execution policy helps protect you from scripts that you do not trust. Changing the execution policy
might expose you to the security risks described in the about_Execution_Policies help topic at
https:/go.microsoft.com/fwlink/?LinkID=135170. Do you want to change the execution policy?
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "N"): A
PS C:\Users\Administrator> Get-ExecutionPolicy
Unrestricted
PS C:\Users\Administrator>
PS C:\Windows\system32> Invoke-Command -Session $hostlist -FilePath "C:\scripts\test.ps1"
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName PSComputerName
------- ------ ----- ----- ------ -- -- ----------- --------------
265 12 2652 11432 0.20 492 1 winlogon WS2019EN
231 11 2268 8716 0.09 3664 2 winlogon WS2019EN
# 远程主机就算是Restricted也可以执行呢。。。
PS C:\Windows\system32> Invoke-Command -Session $hostlist -ScriptBlock { Get-ExecutionPolicy }
PSComputerName RunspaceId Value
-------------- ---------- -----
WS2019EN 27cf2a8b-8faa-4062-9b2b-e84aa580f6a9 Restricted
温馨提示:无法远程本机
PS C:\Windows\system32> hostname
W10ENT-01
PS C:\Windows\system32> Enter-PSSession -ComputerName W10ENT-01 -Credential localhost\administrators
Enter-PSSession : Connecting to remote server W10ENT-01 failed with the following error message : Access is denied. For more
information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ Enter-PSSession -ComputerName W10ENT-01 -Credential localhost\adminis ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (W10ENT-01:String) [Enter-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed
附录
设置能远程登录的用户组
打开本地组策略
按Win+R,打开运行,输入gpedit.msc按回车。
找到【计算机设置】 - 【Windows设置】- 【安全设置】 - 【本地策略】 - 【用户权限管理】 - 允许通过远程桌面服务登录
默认允许,Administrators和“Remote Desktop Users”两个组,一般不需要改,如果要改直接在设置面板里追加即可。
最佳实践应该是通过把用户,或者组加入“Remote Desktop Users”来获取远程登录权限