簡體   English   中英

要求OMS的Azure自動化腳本

[英]Azure Automation script to request OMS

我在PowerShell中編寫了一個自動化腳本,每天早上給我有關我們的Azure訂閱(Vm,自動化作業,警報等)的報告。 現在,我要添加一個新功能,該功能可以在我的計算機上正常運行,但是在從Automation運行時失敗,並且我不知道如何使它正常工作。

在我的計算機上運行良好(VS代碼/ PS 5.1 / PS 4.0)

$omsRGname = "xxx"
$omsWorkspaceName = "xxx"
$omsQueryThreat = 'Type=ProtectionStatus ThreatStatusRank!=150 ThreatStatusRank!=470 | select Computer,Threat,ThreatStatus'
$ArrayThreat = New-Object System.Collections.ArrayList

function OmsRequest {
    Param(
        [parameter(Position = 0, Mandatory = $true)]
        $omsRG,
        [parameter(Position = 1, Mandatory = $true)]
        $omsWorkspace,
        [parameter(Position = 2, Mandatory = $true)]
        $omsQuery
    )
    Process {
        Import-Module AzureRm.OperationalInsights
        $error.clear()
        $Result.clear
        $script:Result = Get-AzureRmOperationalInsightsSearchResults -ResourceGroupName $omsRG -WorkspaceName $omsWorkspace -Query $omsQuery
        $reqIdParts = $Result.Id.Split("/")
        $reqId = $reqIdParts[$reqIdParts.Count - 1]
        $wait = Get-Date
        while ($Result.Metadata.Status -eq "Pending" -and $error.Count -eq 0) {
            $Result = Get-AzureRmOperationalInsightsSearchResults -WorkspaceName $omsWorkspace -ResourceGroupName $omsRG -Id $reqId
            #debug
            $elapsedTime = $(get-date) - $wait
            Write-Output "Elapsed: $elapsedTime -- Status: $($Result.Metadata.Status)"
            Write-Output "Count: $($Result.Count)"
        }
    }
}

OmsRequest $omsRGname $omsWorkspaceName $omsQueryThreat
#debug
Write-Output "VALUEOUT:" $Result.Value
#
$OMSComputers = $Result.Value | ConvertFrom-Json
if ($OMSComputers) {
    foreach ( $ThreatDetails in $OMSComputers) {
        <#write "$(get-date($ThreatDetails.__metadata.TimeGenerated) -format G) - $($ThreatDetails.Computer) - $($ThreatDetails.Threat) - $($ThreatDetails.ThreatStatus)"#>
        $ThDetails = [PSCustomObject] @{
            Date         = (get-date($ThreatDetails.__metadata.TimeGenerated) -format G);
            Computer     = $ThreatDetails.Computer;
            Threat       = $ThreatDetails.Threat;
            ThreatStatus = $ThreatDetails.ThreatStatus;
        }
        $ArrayThreat.Add($ThDetails) |Out-Null
    }
}
else {Write-Output "OK"}

$ArrayThreat

從我的本地計算機

Elapsed: 00:00:00.4270000 -- Status: Successful
Count: 1

Date                Computer      Threat                   ThreatStatus
----                --------      ------                   ------------
29/06/2017 12:55:37 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 11:48:28 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 10:55:37 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 09:55:38 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 08:48:28 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 08:48:28 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 07:55:37 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 07:55:37 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 06:48:28 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 06:48:28 xxx.local     Virus:ALisp/Bursted.DT   Quarantined

當我從自動化運行代碼時,出現此錯誤

ConvertFrom-Json : The input object cannot be bound to any parameters for the command either because the command does 
not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.
At line:164 char:33
+ $OMSComputers = $Result.Value | ConvertFrom-Json
+                                 ~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: ({
  "Computer"...ng": {}
  }
}:JObject) [ConvertFrom-Json], ParameterBindingException
    + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.ConvertFromJsonCommand

好吧,我的錯誤在這里

$OMSComputers = $Result.Value | ConvertFrom-Json

當我查看它的值時,我得到了它(只是從$ Result.Value給出的列表中選取了一個屬性)

VALUEOUT:

Name                       : Computer
Type                       : Property
HasValues                  : True
First                      : {}
Last                       : {}
Count                      : 1
Parent                     : {Computer, Threat, ThreatStatus, __metadata}
Root                       : {Computer, Threat, ThreatStatus, __metadata}
Next                       : {}
Previous                   : 
Path                       : Computer
LineNumber                 : 0
LinePosition               : 0
IsReadOnly                 : False
AllowNew                   : True
AllowEdit                  : True
AllowRemove                : True
SupportsChangeNotification : True
SupportsSearching          : False
SupportsSorting            : False
IsSorted                   : False
SortProperty               : 
SortDirection              : Ascending
IsFixedSize                : False
SyncRoot                   : System.Object
IsSynchronized             : False

isee這條線

Keys                       : {Computer, Threat, ThreatStatus, __metadata}

我試圖將其解析為哈希表,但沒有結果。

有誰有其他創造性的方法來解決這個問題? 謝謝

編輯:我只在這里過去我的功能。 但是在完整腳本中,我連接良好並且PS模塊已經存在(如果功能不能告訴我,則找不到RG,盡管如此,我還是單擊了並從您的鏈接添加模塊)。 如果我查看$ result內容,則會得到查詢結果。

{
    "Computer": "xxx.local",
    "Threat": "Virus:ALisp/Bursted.DT",
    "ThreatStatus": "Quarantined",
    "__metadata": {
        "Type": "ProtectionStatus",
        "TimeGenerated": "2017-06-29T10:55:37.77Z",
        "highlighting": {}
    }
}

當我要求它的類型時

Newtonsoft.Json.Linq.JObject

因此,我導入了Newtonsoft.Json模塊,並嘗試從這種Json進行轉換,但是它也失敗了。

看來我的OMS查詢正在運行(我在$ Result中有一個結果),但是當Automation嘗試使用'ConvertFrom-Json'進行轉換時,它將失敗。

#debug
Write-Output "VALUEOUT:"
Write-Output "Get-variable RESULT"
Get-Variable Result -ValueOnly |format-list
$OMSComputers = $Result.Value | ConvertFrom-Json

輸出:

    VALUEOUT:
    Get-variable RESULT

    Id       : subscriptions/xxx/providers/Microsoft.Operatio
               nalInsights/workspaces/xxx/search/xxx|10.1.0.27|2017-07-05T14-33-52Z
    Metadata : Microsoft.Azure.Commands.OperationalInsights.Models.PSSearchMetadata
    Error    : 
    Value    : {"Computer": "xxx.local" "Threat": "Virus:ALisp/Bursted.DT" "ThreatStatus": "Quarantined" 
               "__metadata": {
                 "Type": "ProtectionStatus",
                 "TimeGenerated": "2017-06-29T10:55:37.77Z",
                 "highlighting": {}
               }, "Computer": "xxx.local" "Threat": "Virus:ALisp/Bursted.DT" "ThreatStatus": "Quarantined" 
               "__metadata": {
                 "Type": "ProtectionStatus",
                 "TimeGenerated": "2017-06-29T09:48:28.42Z",
                 "highlighting": {}
               }, "Computer": "xxx.local" "Threat": "Virus:ALisp/Bursted.DT" "ThreatStatus": "Quarantined" 
               "__metadata": {
                 "Type": "ProtectionStatus",
                 "TimeGenerated": "2017-06-29T08:55:37.757Z",
                 "highlighting": {}
               }, "Computer": "xxx.local" "Threat": "Virus:ALisp/Bursted.DT" "ThreatStatus": "Quarantined" 
               "__metadata": {
                 "Type": "ProtectionStatus",
                 "TimeGenerated": "2017-06-29T07:55:38.327Z",
                 "highlighting": {}
               }...}

ConvertFrom-Json : The input object cannot be bound to any parameters for the command either because the command does 

not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.

At line:65 char:33

+ $OMSComputers = $Result.Value | ConvertFrom-Json

+                                 ~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidArgument: ({

  "Computer"...ng": {}

  }

}:JObject) [ConvertFrom-Json], ParameterBindingException

    + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.ConvertFromJsonCommand

我不明白為什么ConvertFrom-Json失敗:/

在Azure自動化帳戶中,它不通過使用Import-Module AzureRm.OperationalInsights支持導入模塊。 您的錯誤根源是$script:Result為null。 您需要將AzureRm.OperationalInsights導入您的Azure自動化帳戶。 請參考以下步驟:

1.打開鏈接

2.單擊“ Deploy to Azure Automation

Import-Module AzureRm.OperationalInsights在您的Import-Module AzureRm.OperationalInsightsImport-Module AzureRm.OperationalInsights

注意:在執行Get-AzureRmOperationalInsightsSearchResults ,根據您Get-AzureRmOperationalInsightsSearchResults ,您需要登錄到運行手冊中的Azure,看來您沒有此步驟。 如果您不這樣做,請將其添加到您的Runbook。

以下運行手冊對我有效。

$connectionName = "AzureRunAsConnection"
try
{
    # Get the connection "AzureRunAsConnection "
    $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName         

    "Logging in to Azure..."
    Add-AzureRmAccount `
        -ServicePrincipal `
        -TenantId $servicePrincipalConnection.TenantId `
        -ApplicationId $servicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint 
}
catch {
    if (!$servicePrincipalConnection)
    {
        $ErrorMessage = "Connection $connectionName not found."
        throw $ErrorMessage
    } else{
        Write-Error -Message $_.Exception
        throw $_.Exception
    }
}

##
$omsRGname = "shuivm"
$omsWorkspaceName = "shuitest"
$omsQueryThreat = 'Type=ProtectionStatus ThreatStatusRank!=150 ThreatStatusRank!=470 | select Computer,Threat,ThreatStatus'
$ArrayThreat = New-Object System.Collections.ArrayList

function OmsRequest {
    Param(
        [parameter(Position = 0, Mandatory = $true)]
        $omsRG,
        [parameter(Position = 1, Mandatory = $true)]
        $omsWorkspace,
        [parameter(Position = 2, Mandatory = $true)]
        $omsQuery
    )
    Process {

        $error.clear()
        $Result.clear
        $script:Result = Get-AzureRmOperationalInsightsSearchResults -ResourceGroupName $omsRG -WorkspaceName $omsWorkspace -Query $omsQuery
        $reqIdParts = $Result.Id.Split("/")
        $reqId = $reqIdParts[$reqIdParts.Count - 1]
        $wait = Get-Date
        while ($Result.Metadata.Status -eq "Pending" -and $error.Count -eq 0) {
            $Result = Get-AzureRmOperationalInsightsSearchResults -WorkspaceName $omsWorkspace -ResourceGroupName $omsRG -Id $reqId
            #debug
            $elapsedTime = $(get-date) - $wait
            Write-Output "Elapsed: $elapsedTime -- Status: $($Result.Metadata.Status)"
            Write-Output "Count: $($Result.Count)"
        }
    }
}

OmsRequest $omsRGname $omsWorkspaceName $omsQueryThreat
#debug
Write-Output "VALUEOUT:" $Result.Value
#
$OMSComputers = $Result.Value | ConvertFrom-Json
if ($OMSComputers) {
    foreach ( $ThreatDetails in $OMSComputers) {
        <#write "$(get-date($ThreatDetails.__metadata.TimeGenerated) -format G) - $($ThreatDetails.Computer) - $($ThreatDetails.Threat) - $($ThreatDetails.ThreatStatus)"#>
        $ThDetails = [PSCustomObject] @{
            Date         = (get-date($ThreatDetails.__metadata.TimeGenerated) -format G);
            Computer     = $ThreatDetails.Computer;
            Threat       = $ThreatDetails.Threat;
            ThreatStatus = $ThreatDetails.ThreatStatus;
        }
        $ArrayThreat.Add($ThDetails) |Out-Null
    }
}
else {Write-Output "OK"}

$ArrayThreat

我對命令有完全相同的問題: $Result.Value | ConvertFrom-Json $Result.Value | ConvertFrom-Json

在自動化運行手冊和本地執行中均會發生此行為

這是我的解決方法,可使用ForEach從查詢中提取$ result.Value並將值傳遞給哈希表:

  $dynamicQuery = "* | measure count() by Type"
$now = Get-Date
$StartDateAndTime = $now.AddHours(-24).ToString("yyyy-MM-ddTHH:mm:ss")

$EndDateAndTime = $now.ToString("yyyy-MM-ddTHH:mm:ss")

$result = Get-AzureRmOperationalInsightsSearchResults `
-ResourceGroupName $ResourceGroupName `
-WorkspaceName $WorkSpaceName `
-Query $dynamicQuery `
-Start $StartDateAndTime `
-End $EndDateAndTime 

 $queryResults = new-object System.Collections.Hashtable

Foreach ($item in $result.value)
{
 $obj1 = $item["Type"].ToString()
   $obj2= $item["AggregatedValue"].ToString()
  [void]$queryResults.Add($obj1,$obj2)
}

Write-Output $queryResults

我在這里添加了一個問題,因為這不是該模塊的文檔記錄方式,也不是一個優雅的解決方案: https : //github.com/Azure/azure-powershell/issues/4256

感謝你的幫助 :)

這是模塊損壞時我使用的調試代碼(已經添加到我們的生產MorningReport腳本中)

###Query OMS for malware state
#MorningMalwareDebug region Authentication
Write-Verbose ""
Write-Verbose "------------------------ Authentication ------------------------"
Write-Verbose "Logging in to Azure ..."
try {
    $connectionName = "AzureRunAsConnection"
    # Get the connection "AzureRunAsConnection "
    $servicePrincipalConnection = Get-AutomationConnection -Name $connectionName         
    $null = Add-AzureRmAccount `
        -ServicePrincipal `
        -TenantId $servicePrincipalConnection.TenantId `
        -ApplicationId $servicePrincipalConnection.ApplicationId `
        -SubscriptionName "xxxx" `
        -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint

    Write-Verbose "Successfully logged in to Azure." 
} 
catch {
    if (!$servicePrincipalConnection) {
        $ErrorMessage = "Connection $connectionName not found."
        throw $ErrorMessage
    } 
    else {
        Write-Error -Message $_.Exception
        throw $_.Exception
    }
}
#MorningMalwareDebug endregion Authentication
####
#MorningMalwareDebug region Function
function OmsRequest {
    Param(
        [parameter(Position = 0, Mandatory = $true)]
        $omsRG,
        [parameter(Position = 1, Mandatory = $true)]
        $omsWorkspace,
        [parameter(Position = 2, Mandatory = $true)]
        $omsQuery
    )
    Process {
        Import-Module AzureRm.OperationalInsights
        $error.clear()
        $Result.clear
        $script:Result = Get-AzureRmOperationalInsightsSearchResults -ResourceGroupName $omsRG -WorkspaceName $omsWorkspace -Query $omsQuery -Start $FromStartDate -End $ToEndDate
        $reqIdParts = $Result.Id.Split("/")
        $reqId = $reqIdParts[$reqIdParts.Count - 1]
        $wait = Get-Date
        while ($Result.Metadata.Status -eq "Pending" -and $error.Count -eq 0) {
            $Result = Get-AzureRmOperationalInsightsSearchResults -WorkspaceName $omsWorkspace -ResourceGroupName $omsRG -Id $reqId
            $elapsedTime = $(get-date) - $wait
            Write-Output "Elapsed:" $elapsedTime "-- Status:" $Result.Metadata.Status
        }
    }
}
#MorningMalwareDebug endregion Function
####
#MorningMalwareDebug region Variables
$now = Get-Date
$FromStartDate = $now.AddHours(-24).ToString("yyyy-MM-ddTHH:mm:ss")
$ToEndDate = $now.ToString("yyyy-MM-ddTHH:mm:ss")
$omsRGname = "xxxx"
$omsWorkspaceName = "xxxx"
$omsQueryThreat = 'Type=ProtectionStatus ThreatStatusRank!=150 ThreatStatusRank!=470 | select Computer,Threat,ThreatStatus'
$ArrayThreat = New-Object System.Collections.ArrayList
#MorningMalwareDebug endregion Variables
####
#MorningMalwareDebug region Main
OmsRequest $omsRGname $omsWorkspaceName $omsQueryThreat
if ($Result.value) {
    $ArrayThreat.clear()
    Foreach ($ThreatDetails in $Result.value) {
        $ThDetails = [PSCustomObject] @{
            Computer     = ($ThreatDetails["Computer"].ToString()).split('.')[0];
            Threat       = $ThreatDetails["Threat"].ToString();
            ThreatStatus = $ThreatDetails["ThreatStatus"].ToString();
        }
        $ArrayThreat.Add($ThDetails)
    }
    Write-Output $ArrayThreat
}
else {write-output "Pas de menace"}
#MorningMalwareDebug endregion Main
####
#MorningMalwareDebug region BuildMail
#MorningMalwareDebug endregion BuildMail
####
#MorningMalwareDebug region SendMail
#MorningMalwareDebug endregion SendMail

暫無
暫無

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

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