簡體   English   中英

使用powershell登錄azure帳戶而不彈出

[英]login to azure account without popup using powershell

我正在嘗試使用 powershell 創建 Azure VM。我也有創建它的腳本。

首先,我需要登錄 Azure 帳戶:

Login-AzureRMAccount

這會彈出一個輸入憑據的窗口。

其次,我需要運行以下腳本:

$UserName = "username"
$Password = ConvertTo-SecureString "password" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($UserName, $Password)    
New-AzureRmVm `
    -ResourceGroupName "RG1" `
    -Name "VM1" `
    -ImageName "Image1" `
    -Location "West US" `
    -Credential $psCred

這是成功創建VM。
但是現在,我需要讓這些腳本在需要時自動運行。 我面臨的問題是,登錄步驟會彈出一個窗口來輸入我不想要的憑據。 所以我嘗試過這樣的事情,但沒有奏效。

$username = "loginname@organization.com"
$SecurePassword = ConvertTo-SecureString "password" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($username, $SecurePassword)
Login-AzureRmAccount -Credential $cred 

它給出的錯誤消息是:

Login-AzureRmAccount : accessing_ws_metadata_exchange_failed: Accessing WS metadata exchange failed: The underlying connection was closed: An unexpected error occurred on a send.
At line:4 char:1
+ Login-AzureRmAccount -Credential $cred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Connect-AzureRmAccount], AadAuthenticationFailedException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand

誰能告訴我這是什么意思以及如何糾正? 謝謝!

如果您打算使用 PowerShell 將任何服務自動化到 Azure 中,那么我建議您使用Service Principal而不是您自己的憑據來連接 azure,這將是一種安全的連接方式。

什么是服務主體?

Azure 服務主體是用戶創建的應用、服務和自動化工具用來訪問特定 Azure 資源的安全標識。 將其視為具有特定角色和嚴格控制權限的“用戶身份”(用戶名和密碼或證書)。 它只需要能夠做特定的事情,不像一般的用戶身份。 如果您只授予它執行其管理任務所需的最低權限級別,它會提高安全性。

按照本教程創建服務主體

我還在Microsoft 庫中發布了一個示例PowerShell 工作流程,用於創建服務主體,您也可以遵循該流程

創建服務主體后,您可以使用以下 PowerShell 命令登錄 azure,而不會出現任何彈出窗口

$applicationId = "<service prinicple application id>";
$securePassword = "<service prinicple password>" | ConvertTo-SecureString -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $applicationId, $securePassword
Connect-AzureRmAccount -ServicePrincipal -Credential $credential -TenantId "<your tenantid>"

更新1:

由於某種原因/錯誤,上述內容將失敗。 參考這個github問題

為了解決這個

在腳本前添加兩行

Import-Module -Name AzureRM.Profile
Remove-AzureRmAccount

更新 2:

AzureRM 將不再接收新的 cmdlet 或功能。 但是,AzureRM 模塊仍處於官方維護狀態,並將在 2020 年 12 月之前修復錯誤。

您必須使用新的 Azure PowerShell Az 模塊

基本上,您可以通過將 Logging 部分添加為 $PSProfile 的一部分來為所有 PowerShell 會話實現此目的。 我使用這個技巧跳過登錄彈出窗口,所以每當我打開 powershell 時,我的帳戶都會自動登錄。

  • 以管理員身份打開 Windows PowerShell
  • 輸入記事本 $profile
  • 將打開一個記事本文件,您可以在此處粘貼以下代碼以在打開時自動登錄。

     $username = “” $password = “” $securepasswd = ConvertTo-SecureString $password -AsPlainText -Force $cred = New-Object System.Management.Automation.PSCredential ($username, $ securepasswd) Connect-AzureRmAccount -Credential $cred

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM