远程管理Windows - 命令行以及图形界面

远程管理Windows - 命令行以及图形界面

Windows远程管理简述

Windows远程管理方式

  • GUI:通过【远程桌面】来远程登录
    • 前提
      • 启用远程桌面
      • 用户有远程登录权限(加入组Administrators,或者“Remote Desktop Users”。可以自定义,见附录)
    • 客户端
      • 远程桌面连接:MSTSC
      • mobaxterm等支持RDP协议的客户端
  • CLI:通过WinRM(Powershell)来远程登录
    • 前提
      • 配置并启用WinRM
      • 用户有远程登录权限(加入组Administrators,或者“Remote Desktop Users”)
    • 客户端
      • Powershell(WinRM属于内置模块 / 命令来的?)

温馨提示

  1. Windows 10 Home Edition不支持远程桌面
  2. 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”来获取远程登录权限

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在Linux中,可以使用Ctrl+Alt+F1~F6键来切换到不同命令行界面,其中F1表示第一个命令行界面,F2表示第二个命令行界面,以此类推,F6表示第六个命令行界面。如果需要返回到图形界面,则可以使用Ctrl+Alt+F7键。 ### 回答2: 在Linux操作系统中,切换到命令行界面有多种方式。 1. 使用终端快捷键: 在图形界面中按下Ctrl+Alt+T组合键可以快速打开一个终端窗口。如果是在已经打开的终端窗口中,可以使用Ctrl+Alt+Fn(F1至F6)来切换到不同的文本控制台,Fn后面的数字表示对应的文本控制台。 2. 使用命令行切换: 在图形界面中打开终端窗口后,输入"logout"命令或者"exit"命令可以退出当前的终端会话,返回到图形界面。反之,可以在图形界面中按下Ctrl+Alt+Fn(F1至F6)组合键切换到不同的文本控制台。 3. 使用功能键组合: 在启动Linux操作系统时,会有一个用于选择启动选项的界面(GRUB)。在这个界面中,可以使用方向键选择一个带有“recovery mode”或类似字样的选项,然后按下Enter键进入恢复模式。恢复模式会进入纯命令行界面。 无论使用哪种方式,进入命令行界面后,可以通过输入命令来进行各种操作,例如文件管理、系统配置、软件安装等。命令行界面在某些情况下更加高效和灵活,尤其是在远程管理和系统故障排查等方面。 ### 回答3: 在Linux中,我们可以使用Ctrl+Alt+Fx(F1至F6)键快速切换到命令行界面。每个快捷键对应一个虚拟终端,我们可以在这些终端之间进行切换。 默认情况下,图形界面运行在第7个虚拟终端(Ctrl+Alt+F7),而命令行界面运行在第1个虚拟终端(Ctrl+Alt+F1)。如果我们想要切换到命令行界面,只需要按下Ctrl+Alt+F1键即可。同理,如果我们想切换回图形界面,只需要按下Ctrl+Alt+F7键即可。通过这种方式,我们可以方便地在图形界面命令行界面之间切换。 在命令行界面中,我们可以通过输入命令来完成各种任务,如文件管理、进程管理、软件安装等。命令行界面通常被认为是更加高效和强大的工具,尤其是在服务器环境下。使用命令行界面可以更好地控制和管理系统,尤其是在遇到问题时,命令行界面可以提供更多的调试和故障排除选项。 需要注意的是,虽然Linux提供了多个虚拟终端,但大多数情况下我们只需要使用其中一个。只有在某些特定情况下,如系统崩溃或需要进行故障排除时,我们才需要切换到其他虚拟终端。 总之,Linux提供了快速切换到命令行界面的方法,通过Ctrl+Alt+Fx键可以方便地在图形界面命令行界面之间切换。命令行界面提供了更强大和灵活的功能,可以用于系统管理和故障排除。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值