在Windows PowerShell中启用远程命令(Windows远程管理)

时间:2020-03-21 11:49:28  来源:igfitidea点击:

Windows PowerShell 2.0使用WS-Management(WinRM 2.0),允许在远程计算机上调用脚本和cmdlet。

要实现的目标

我们有两个Windows Server 2008 VM:

  • IP地址为1.1.1.1的Web服务器A(DNS:remote.example.com)
  • 带有IP 2.2.2.2的服务器B

我们要从服务器B在Web服务器A上运行PowerShell命令。

配置

服务器A

打开Windows PowerShell,并将Web服务器配置为接收通过WS-Management发送的PowerShell远程命令。
请注意,在Windows Server 2012上,默认情况下启用Windows PowerShell远程处理。

PS> Enable-PSRemoting -Force

将服务器的B IP地址添加到受信任的主机:

PS> Set-Item wsman:\localhost\client\trustedhosts 2.2.2.2

要查看受信任主机的列表,请执行以下操作:

PS> get-item wsman:\localhost\client\trustedhosts
WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Client
Name            Value         Type
----            -----         ---
TrustedHosts    2.2.2.2       System.String

重新启动WinRM服务,并检查服务器是否正在侦听TCP端口5985:

PS> Restart-Service WinRM
PS> netstat -na | findstr :5985
  TCP    0.0.0.0:5985           0.0.0.0:0              LISTENING
  TCP    [::]:5985              [::]:0                 LISTENING

我们也可以使用以下命令查看WinRM正在侦听的特定IP:

PS> winrm enumerate winrm/config/listener
Listener
    Address = *
    Transport = HTTP
    Port = 5985
    Hostname
    Enabled = true
    URLPrefix = wsman
    CertificateThumbprint
    ListeningOn = 10.1.2.3, 127.0.0.1, ::1, [OUTPUT TRUNCATED]

需要配置防火墙以允许到TCP端口5985的通信。

服务器B

在服务器B上运行以下命令:

PS> Enable-PSRemoting -Force

将服务器的IP地址和DNS名称添加到受信任的主机:

PS> Set-Item wsman:\localhost\client\trustedhosts 1.1.1.1
PS> Set-Item wsman:\localhost\client\trustedhosts remote.example.com

重新启动WinRM服务:

PS> Restart-Service WinRM

测试Windows远程管理与服务器A的连接:

PS> Test-WsMan 1.1.1.1
wsmid           : http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd
ProtocolVersion : http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd
ProductVendor   : Microsoft Corporation
ProductVersion  : OS: 0.0.0 SP: 0.0 Stack: 2.0

使用Windows远程管理

具有纯文本凭证的非交互式登录

PS> $password = ConvertTo-SecureString "plaintext-password" -AsPlainText -Force
PS> $cred= New-Object System.Management.Automation.PSCredential ("username", $password )
PS> Enter-PSSession -ComputerName 1.1.1.1 -Credential $cred
[1.1.1.1]: PS C:\Users\username\Documents>

在远程系统上运行命令

下面的示例显示如何停止IIS站点,该站点称为“教程 ”,更改其物理路径,然后使该站点重新联机:

PS> Invoke-Command -ComputerName 1.1.1.1 -Credential $cred -ScriptBlock {C:\Windows\System32\inetsrv\appcmd.exe stop site "blog"}
PS> Invoke-Command -ComputerName 1.1.1.1 -Credential $cred -ScriptBlock {C:\Windows\System32\inetsrv\appcmd.exe set vdir "blog/" -physicalPath:"C:\inetpub\blog_new"}
PS> Invoke-Command -ComputerName 1.1.1.1 -Credential $cred -ScriptBlock {C:\Windows\System32\inetsrv\appcmd.exe start site "blog"}