在远程服务器上使用 PowerShell 安装证书

D.R*_*.R. 7 powershell certificate

我想在远程服务器上安装使用 makecert.exe 创建的证书 (X.509)。我无法使用 psexec 或类似的东西,但必须使用 PowerShell。

  • 服务器操作系统:Windows Server 2008 R2
  • PowerShell 版本:4

问题:如何使用 PowerShell 在远程服务器上安装证书。

xx1*_*1xx 6

场景:ServerA 有 SSL 证书,ServerB 想要导入 SSL 证书

  1. 定义两个变量(仅限 ServerB):

    $afMachineName = "SomeMachineNameOrIp"
    $certSaveLocation = "c:\temp\Cert.CER"
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在两台机器上启用信任(ServerA 和 ServerB):

    Function enableRemotePS() {
        Enable-PSRemoting -Force
        Set-Item wsman:\localhost\client\trustedhosts $afMachineName -Force
        Restart-Service WinRM
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 保存证书(仅限 ServerB):

    Function saveCert([string]$machineName,[string]$certSaveLocation) {
        Invoke-Command -ComputerName $machineName -ArgumentList $certSaveLocation -ScriptBlock {
            param($certSaveLocation)
            $cert = dir Cert:\LocalMachine\Root | where {$_.Subject -eq "CN=YOURCERTNAME" };
            $certBytes = $cert.Export("cert");
            [system.IO.file]::WriteAllBytes($certSaveLocation, $certBytes);
        }
    
        Copy-Item -Path \\$machineName\c$\temp\CertAF.CER -Destination $certSaveLocation
    }
    
    Run Code Online (Sandbox Code Playgroud)
  4. 导入证书(仅限 ServerB)

    Function importCert([string]$certSaveLocation) {
        $CertToImport = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $certSaveLocation
    
        $CertStoreScope = "LocalMachine"
        $CertStoreName = "Root"
        $CertStore = New-Object System.Security.Cryptography.X509Certificates.X509Store $CertStoreName, $CertStoreScope
    
        # Import The Targeted Certificate Into The Specified Cert Store Name Of The Specified Cert Store Scope
        $CertStore.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
        $CertStore.Add($CertToImport)
        $CertStore.Close()
    }
    
    Run Code Online (Sandbox Code Playgroud)


ulr*_*chb 4

要导入 PFX 文件,您可以使用Import-PfxCertificate,例如

Import-PfxCertificate -FilePath YOUR_PFX_FILE.pfx -Password (ConvertTo-SecureString -String "THE_PFX_PASSWORD" -AsPlainText -Force)
Run Code Online (Sandbox Code Playgroud)

要在远程计算机上执行此操作,您可以使用Invoke-Command -ComputerName(并使用 PFX 文件的 UNC 路径)。