close

Windows 遠端管理預設為停用狀態,非網域的環境下啟用踩了一些雷,本篇將紀錄啟用流程和不同的連線方式

說明:

  • 本篇文章下 Server 端為被連線端,Client 為連線端,兩邊都需要做一些設定才能夠成功透過 PowerShell/GUI Tool 管理遠端電腦
  • PowerShell 遠端管理有兩種方式 (HTTP和HTTPS)
  • 如果要在非網域環境下透過 HTTP 協定管理遠端電腦,Client 和 Server 都需要互相加入信任清單(白名單),或是透過 HTTPS 管理(缺點是連線必須使用電腦名稱、需手動產生憑證)

 

前置設定(Server):

通用設定 (不管是不是走 HTTPS,不管有沒有加入網域):

Enable-PSRemoting –Force
WinRM quickconfig

走 HTTP:

加入遠端電腦到信任清單中 ( Client 電腦也要設定 TrustedHosts )

WinRM set winrm/config/client '@{TrustedHosts="<遠端電腦位置/電腦名稱(可用逗號分隔,或使用 * 代表全部信任)>"}'

示範:

WinRM set winrm/config/client '@{TrustedHosts="computername"}'
WinRM set winrm/config/client '@{TrustedHosts="192.168.0.100,192.168.0.101"}'
WinRM set winrm/config/client '@{TrustedHosts="192.168.0.199"}'
WinRM set winrm/config/client '@{TrustedHosts="*"}'

加入防火牆規則

New-NetFireWallRule -DisplayName "Windows Remote Management (HTTP-In)" -Direction Inbound -Protocol TCP -LocalPort 5985 -Action Allow

 

走 HTTPS:

產生憑證

New-SelfSignedCertificate -DnsName "<HOSTNAME>","<HOSTNAME.FQDN>"

取得憑證指紋

$Thumbprint = Get-ChildItem cert:\LocalMachine\My | Where-Object { $_.Subject -eq "CN=<HOSTNAME>" }

啟用 HTTPS (要用 cmd 執行,不要用 powershell)

winrm create winrm/config/Listener?Address=*+Transport=HTTPS @{Hostname="HOSTNAME";CertificateThumbprint=$Thumbprint}

加入防火牆規則

New-NetFireWallRule -DisplayName "Windows Remote Management (HTTPS-In)" -Direction Inbound -Protocol TCP -LocalPort 5986 -Action Allow

如果找不到電腦名稱,可設定 host

Add-Content -Path "$env:windir\System32\drivers\etc\hosts" -Value "192.168.0.100 <HOSTNAME>"

 

連線指令:

上面設定完後記得重起 WinRM 服務

Restart-Service WinRM

1. 使用互動式操作

HTTP:

Enter-PSSession <Computer-Name/IP Address> -Credential (Get-Credential)

HTTPS:

Enter-PSSession <Computer-Name/IP Address> -Credential (Get-Credential) -UseSSL

Enter-PSSession <Computer-Name/IP Address> -Credential (Get-Credential) -UseSSL -SessionOption (New-PsSessionOption –SkipCACheck)

Exit-PSSession

2. 直接執行遠端命令(可以同時在多台遠端電腦執行)

HTTP:

Invoke-Command -ComputerName <ComputerName1>, <ComputerName2>,<IP Address> -Credential (Get-Credential) -ScriptBlock {<Remote-Command>}

HTTPS:

Invoke-Command -ComputerName <ComputerName1>, <ComputerName2>,<IP Address> -Credential (Get-Credential) -ScriptBlock {<Remote-Command>} -UseSSL -SessionOption (New-PsSessionOption –SkipCACheck)

示範:

Invoke-Command -ComputerName 192.168.0.1 -Credential "Administrator" -ScriptBlock {<Command>}

一行直接帶密碼執行版(建議搭配 Powershell script file 改成以參數方式帶入帳號密碼):

Invoke-Command -ComputerName 192.168.0.1 -Credential (New-Object System.Management.Automation.PSCredential ('Administrator', (ConvertTo-SecureString 'P@ssw0rd' -AsPlainText -Force))) -ScriptBlock {<Command>}

arrow
arrow
    全站熱搜

    AwEi 發表在 痞客邦 留言(0) 人氣()