为 Azure Resource Manager 中的虚拟机设置 WinRM 访问权限Setting up WinRM access for Virtual Machines in Azure Resource Manager

为 VM 设置 WinRM 连接需执行以下步骤Here are the steps you need to take to set up a VM with WinRM connectivity

  1. 创建密钥保管库Create a Key Vault
  2. 创建自签名证书Create a self-signed certificate
  3. 将自签名证书上传到密钥保管库Upload your self-signed certificate to Key Vault
  4. 获取密钥保管库中自签名证书的 URLGet the URL for your self-signed certificate in the Key Vault
  5. 创建 VM 时引用自签名证书 URLReference your self-signed certificates URL while creating a VM

步骤 1:创建密钥保管库Step 1: Create a Key Vault

可使用以下命令来创建密钥保管库You can use the below command to create the Key Vault

Connect-AzAccount -Environment AzureChinaCloud
New-AzKeyVault -VaultName "<vault-name>" -ResourceGroupName "<rg-name>" -Location "<vault-location>" -EnabledForDeployment -EnabledForTemplateDeployment

步骤 2:创建自签名证书Step 2: Create a self-signed certificate

可使用此 PowerShell 脚本创建自签名证书You can create a self-signed certificate using this PowerShell script

$certificateName = "somename"

$thumbprint = (New-SelfSignedCertificate -DnsName $certificateName -CertStoreLocation Cert:\CurrentUser\My -KeySpec KeyExchange).Thumbprint

$cert = (Get-ChildItem -Path cert:\CurrentUser\My\$thumbprint)

$password = Read-Host -Prompt "Please enter the certificate password." -AsSecureString

Export-PfxCertificate -Cert $cert -FilePath ".\$certificateName.pfx" -Password $password

步骤 3:将自签名证书上传到密钥保管库Step 3: Upload your self-signed certificate to the Key Vault

将证书上传到在步骤 1 中创建的密钥保管库之前,需将其转换为 Microsoft.Compute 资源提供程序可识别的格式。Before uploading the certificate to the Key Vault created in step 1, it needs to converted into a format the Microsoft.Compute resource provider will understand. 以下 PowerShell 脚本将允许执行该操作The below PowerShell script will allow you do that

$fileName = "<Path to the .pfx file>"
$fileContentBytes = Get-Content $fileName -Encoding Byte
$fileContentEncoded = [System.Convert]::ToBase64String($fileContentBytes)

$jsonObject = @"
{
  "data": "$filecontentencoded",
  "dataType" :"pfx",
  "password": "<password>"
}
"@

$jsonObjectBytes = [System.Text.Encoding]::UTF8.GetBytes($jsonObject)
$jsonEncoded = [System.Convert]::ToBase64String($jsonObjectBytes)

$secret = ConvertTo-SecureString -String $jsonEncoded -AsPlainText -Force
Set-AzKeyVaultSecret -VaultName "<vault name>" -Name "<secret name>" -SecretValue $secret

步骤 4:获取密钥保管库中自签名证书的 URLStep 4: Get the URL for your self-signed certificate in the Key Vault

预配 VM 时,Microsoft.Compute 资源提供程序需要指向密钥保管库中密钥的 URL。The Microsoft.Compute resource provider needs a URL to the secret inside the Key Vault while provisioning the VM. 这会使 Microsoft.Compute 资源提供程序能够下载密钥,并在 VM 上创建等效证书。This enables the Microsoft.Compute resource provider to download the secret and create the equivalent certificate on the VM.

备注

密钥 URL 还需要包含版本。The URL of the secret needs to include the version as well. 示例 URL 类似于以下链接:https://contosovault.vault.azure.cn:443/secrets/contososecret/01h9db0df2cd4300a20ence585a6s7veAn example URL looks like below https://contosovault.vault.azure.cn:443/secrets/contososecret/01h9db0df2cd4300a20ence585a6s7ve

模板Templates

可使用以下代码获取模板中 URL 的链接You can get the link to the URL in the template using the below code

"certificateUrl": "[reference(resourceId(resourceGroup().name, 'Microsoft.KeyVault/vaults/secrets', '<vault-name>', '<secret-name>'), '2015-06-01').secretUriWithVersion]"

PowerShellPowerShell

可使用以下 PowerShell 命令获取此 URLYou can get this URL using the below PowerShell command

$secretURL = (Get-AzKeyVaultSecret -VaultName "<vault name>" -Name "<secret name>").Id

步骤 5:创建 VM 时引用自签名证书 URLStep 5: Reference your self-signed certificates URL while creating a VM

Azure Resource Manager 模板Azure Resource Manager Templates

通过模板创建 VM 时,在密钥部分和 winRM 部分中引用该证书,如下所示:While creating a VM through templates, the certificate gets referenced in the secrets section and the winRM section as below:

"osProfile": {
      ...
      "secrets": [
        {
          "sourceVault": {
            "id": "<resource id of the Key Vault containing the secret>"
          },
          "vaultCertificates": [
            {
              "certificateUrl": "<URL for the certificate you got in Step 4>",
              "certificateStore": "<Name of the certificate store on the VM>"
            }
          ]
        }
      ],
      "windowsConfiguration": {
        ...
        "winRM": {
          "listeners": [
            {
              "protocol": "http"
            },
            {
              "protocol": "https",
              "certificateUrl": "<URL for the certificate you got in Step 4>"
            }
          ]
        },
        ...
      }
    },

针对上述内容的示例模板可在此处 201-vm-winrm-keyvault-windows 找到A sample template for the above can be found here at 201-vm-winrm-keyvault-windows

此模板的源代码可在 GitHub 上找到Source code for this template can be found on GitHub

备注

必须修改从 GitHub 存储库“azure-quickstart-templates”下载或参考的模板,以适应 Azure 中国云环境。Templates you downloaded or referenced from the GitHub Repo "azure-quickstart-templates" must be modified in order to fit in the Azure China Cloud Environment. 例如,替换某些终结点(将“blob.core.windows.net”替换为“blob.core.chinacloudapi.cn”,将“cloudapp.azure.com”替换为“chinacloudapp.cn”);必要时更改某些不受支持的位置、VM 映像、VM 大小、SKU 以及资源提供程序的 API 版本。For example, replace some endpoints -- "blob.core.windows.net" by "blob.core.chinacloudapi.cn", "cloudapp.azure.com" by "chinacloudapp.cn"; change some unsupported Location,VM images, VM sizes, SKU and resource-provider's API Version when necessary.

PowerShellPowerShell

$vm = New-AzVMConfig -VMName "<VM name>" -VMSize "<VM Size>"
$credential = Get-Credential
$secretURL = (Get-AzKeyVaultSecret -VaultName "<vault name>" -Name "<secret name>").Id
$vm = Set-AzVMOperatingSystem -VM $vm -Windows -ComputerName "<Computer Name>" -Credential $credential -WinRMHttp -WinRMHttps -ProvisionVMAgent -WinRMCertificateUrl $secretURL
$sourceVaultId = (Get-AzKeyVault -ResourceGroupName "<Resource Group name>" -VaultName "<Vault Name>").ResourceId
$CertificateStore = "My"
$vm = Add-AzVMSecret -VM $vm -SourceVaultId $sourceVaultId -CertificateStore $CertificateStore -CertificateUrl $secretURL

步骤 6:连接到 VMStep 6: Connecting to the VM

需要先确保用户的计算机针对 WinRM 远程管理进行了配置,才能连接到 VM。Before you can connect to the VM you'll need to make sure your machine is configured for WinRM remote management. 以管理员身份启动 PowerShell 并执行以下命令以确保已完成设置。Start PowerShell as an administrator and execute the below command to make sure you're set up.

Enable-PSRemoting -Force

备注

如果以上命令无效,可能需要确保 WinRM 服务正在运行。You might need to make sure the WinRM service is running if the above does not work. 可使用 Get-Service WinRMYou can do that using Get-Service WinRM

设置完成后,即可使用以下命令连接到 VMOnce the setup is done, you can connect to the VM using the below command

Enter-PSSession -ConnectionUri https://<public-ip-dns-of-the-vm>:5986 -Credential $cred -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck) -Authentication Negotiate