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

问题描述 投票:0回答:3

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

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

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

powershell certificate
3个回答
6
投票

场景:ServerA 有 SSL 证书,ServerB 希望导入 SSL 证书

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

    $afMachineName = "SomeMachineNameOrIp"
    $certSaveLocation = "c:\temp\Cert.CER"
    
  2. 在两台计算机(ServerA 和 ServerB)上启用信任:

    Function enableRemotePS() {
        Enable-PSRemoting -Force
        Set-Item wsman:\localhost\client\trustedhosts $afMachineName -Force
        Restart-Service WinRM
    }
    
  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
    }
    
  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()
    }
    

4
投票

要导入 PFX 文件,您可以使用

Import-PfxCertificate
,例如

Import-PfxCertificate -FilePath YOUR_PFX_FILE.pfx -Password (ConvertTo-SecureString -String "THE_PFX_PASSWORD" -AsPlainText -Force)

要在远程计算机上执行此操作,您可以使用

Invoke-Command -ComputerName
(并使用 PFX 文件的 UNC 路径)。


0
投票

我为此目的创建了一些脚本:

https://github.com/kevin-bridges/WindowsPowerShell/tree/master/Scripts/certificates

看看它们是否适合您。您可以对每个工具使用 get-help 来检查使用详细信息。

© www.soinside.com 2019 - 2024. All rights reserved.