繼續上文的話題,上文中咱們查詢了Azure中VM的建立記錄,這樣咱們就能夠清晰瞭解到都有哪些用戶建立了VM,如今咱們來把需求擴展下,若是咱們想看到某個用戶的操做記錄,那應該怎麼來作呢?這其實也是個常見的需求,若是有特定的審計要求的話,可能還會用一些第三方產品來作這個事,若是像如今只是想簡單看下記錄,那麼咱們其實直接用PowerShell腳本就能實現了
ide
下邊來看下代碼的內容,實際上是很簡單的
orm
param ( [parameter(Mandatory = $false)] [Int]$MaxRecords = 100000, [parameter(Mandatory = $true)] [string]$User ) function Write-DateTimeMessage { param ( [parameter(Mandatory = $false)] [switch]$Warning, [parameter(Mandatory = $true)] [string]$Message, [parameter(Mandatory = $false)] [string]$ForegroundColor ) if ($Warning) { Write-Warning ($(Get-Date -UFormat '%Y/%m/%d %H:%M:%S') + " * " + $Message) } else { if ($ForegroundColor) { Write-Host ($(Get-Date -UFormat '%Y/%m/%d %H:%M:%S') + " * " + $Message) -ForegroundColor $ForegroundColor } else { Write-Host ($(Get-Date -UFormat '%Y/%m/%d %H:%M:%S') + " * " + $Message) } } } [pscustomobject[]]$UserObjects = $null $Subscriptions = Get-AzureRmSubscription foreach ($subscription in $Subscriptions) { " " "Querying Subscription:" $SubscriptionID = $Subscription.Id $SubscriptionName = $Subscription.Name Select-AzureRmSubscription -SubscriptionId $SubscriptionID -InformationAction SilentlyContinue Write-DateTimeMessage -Message "Retrieving logs, please wait..." $logs = Get-AzureRmLog -ResourceProvider Microsoft.Compute -StartTime (Get-Date).AddDays(-90) -Maxrecord $MaxRecords foreach ($log in $logs) { if ($log.caller -eq $User) { $UserObject = New-Object -TypeName psobject $UserObject | Add-Member -MemberType NoteProperty -Name SubscriptionName -Value $SubscriptionName $UserObject | Add-Member -MemberType NoteProperty -Name SubscriptionID -Value $SubscriptionID $UserObject | Add-Member -MemberType NoteProperty -Name ResourceGroup -Value $log.ResourceGroupName $UserObject | Add-Member -MemberType NoteProperty -Name Caller -Value $log.caller $UserObject | Add-Member -MemberType NoteProperty -Name Operation -Value $log.OperationName.Value $UserObject | Add-Member -MemberType NoteProperty -Name ResourceId -Value $log.ResourceId $UserObject | Add-Member -MemberType NoteProperty -Name Time -Value $log.EventTimestamp $UserObjects += $UserObject } } } $OutputPath = Join-Path -Path ([Environment]::GetFolderPath("Desktop")) -ChildPath ("AzureUserAction-" + $(Get-Date -Format "yyyyMMdd-HHmmss") + ".csv") if ($null -ne $UserObjects) { $UserObjects | Export-Csv -NoTypeInformation -LiteralPath $OutputPath Write-DateTimeMessage -Message "Please check $OutputPath" -Warning } else { Write-DateTimeMessage "Didn't get information, please check" -warning }
咱們來嘗試着運行一下腳本Get-AzureUserActionLog.ps1 -User "xxx@xxx.partner.onmschina.cn", -User的做用是咱們能夠根據這個參數篩選出來特定的用戶blog
腳本執行完成後,能夠在桌面上看到一個csv文件,裏邊會記錄查詢出來log圖片
最後,仍是要提醒一點,由於Azure後臺的限制,這隻能查詢到最近90天以內的log
ip