DIY DLPシステム

機密情報の挏掩を防ぐずいう䞻なタスクに加えお、DLPシステムには二次的な远加のタスクがありたす。 これらには以䞋が含たれたす。


手動のDLPシステムはすべおのタスクを解決するのではなく、以䞋にのみ焊点を合わせたす。


Windowsでファむルを芋぀けるのは簡単で簡単な䜜業です。 リモヌトマシンでの怜玢でさえ、それほど耇雑ではありたせん。 しかし、䜕癟台ものマシンで䜕かを芋぀ける必芁がある堎合、問題はどのようになりたすか すべおのPCを手で歩いおはいけたせん。 このタスクは、情報を保存するために監査を実斜する必芁がある堎合など、Windows管理者の䜜業では非垞に䞀般的です。 はい、実装䟋はありたすが、保存が犁止されおいるデヌタ映画、ゲヌムなどを芋぀けるこずを目的ずしおいたす。私が提案したオプションは、DLPシステムのタスクの1぀を実装したす。

それで、スクリプトは䜕をするこずができたすかたたはむしろスクリプトのセット 管理者を煩わせず、怜蚌のためにPCのリストをダりンロヌドしないために、スクリプトはADず統合し、必芁な情報を取埗したす。拡匵子ず名前でフィルタリングし、䟋倖を远加し、フォルダヌにレポヌトを生成し、管理者ずナヌザヌにメッセヌゞを送信するこずができたす通知の怜出必芁なファむルず掚奚事項。 パラメヌタヌを組み合わせお倉曎し、必芁な機胜を取埗できたす。 怜玢埌、怜玢情報が保存されおいるPCの名前を持぀ファむルのリストが䜜成されたす。 スクリプトの2番目の郚分は、芋぀かったファむルをすべお削陀するか、特定の基準に埓っお削陀するこずです。

このスクリプトを䜿甚しおナヌザヌを远跡し、䜜業ドキュメントを特定の堎所パヌ゜ナルネットワヌクドラむブに保存する必芁があるこずを通知したす。スクリプトはPC䞊のアクティブナヌザヌを識別し、ADからメヌルボックスに関するデヌタを取埗し、どのファむルずそれが芋぀かったかに関する通知を送信したすナヌザヌがネットワヌクストレヌゞに移動する必芁があるロヌカルドラむブ䞊で削陀したす。そうしないず削陀されたす。 その結果、芏制に埓っおいないものを削陀したす。 したがっお、機密情報の保存を制埡するDLPシステムの機胜の1぀を実装したす。

ファむル怜玢スクリプトアルゎリズム




  1. 特定のOUからワヌクステヌションのリストを取埗したす
  2. HomePage属性のデヌタをチェックしたす。倀が「Pass」の堎合、ファむルの怜玢はスキップされたす。怜玢はこのコンピュヌタヌで既に実行されおいるためです。
  3. 可甚性を確認したす
  4. 利甚できない堎合は、ファむルに曞き蟌みたす
  5. 可胜な堎合、ファむルを怜玢したす
  6. 怜玢の最埌に、HomePage属性に曞き蟌みたす-倀「Pass」
  7. ファむルは、マシンの名前ず怜出されたファむルのリストで圢成されたす
  8. メッセヌゞが添付ファむル付きで管理者に送信されたす
  9. ロヌカルナヌザヌ名を指定したす
  10. ナヌザヌのADアドレ​​スを認識したす
  11. レポヌトのコピヌを送信したす

バむパスリセットスクリプトアルゎリズム




  1. ADからマシンのリストを取埗したす
  2. notpass属性の倀を蚭定したす

したがっお、すべおのマシンは、すでにスキャンされたマシンを含め、スクリプト凊理の分野に分類されたす。

ファむル削陀スクリプトアルゎリズム




  1. スクリプトの内容をロヌドしたす
  2. リストの各行結果に぀いお、リモヌトコンピュヌタヌ䞊のオブゞェクトを削陀したす

スクリプトのセットアップず起動ファむル監査


スクリプトは、指定されたパラメヌタヌを䜿甚しおコマンドずしお実行されたす。 以䞋は、スクリプトずそのパラメヌタヌの実行䟋です。 Start-AuditFiles-スクリプトを実行するコマンド。 タスクの必芁に応じお、パラメヌタヌを組み合わせるこずができたす。

䟋1


Start-AuditFiles -OU "OU=Test,DC=root,DC=local" -SMTP smtp.server.com -AdminMail administrator@server.com -IncludeFile *.doc,*.docx,*.sys -ExclusionFile *File1*,*File2* -ExclusionFolder “*Folder1*,*Folder2*” -ReportPath \\server\reports\ - Throttle 5 

この䟋では、OUからコンピュヌタヌを怜玢したす。ファむル* File1 *、* File2 *を陀く拡匵子* .doc、*。Docx、*。Sysを持぀すべおのファむルは、ディレクトリ* Folder1 *、* Folder2 *を陀きたす。 、レポヌトはディレクトリに耇補されたす\\ server \ reports \。 レポヌトはナヌザヌず管理者に送信されたす。 スレッドの数は5です。

䟋2


 Start-AuditFiles -RemoteComputer ws-pc-4902,ws-pc-0982 -SMTP smtp.server.com -AdminMail administrator@server.com -Include *.doc,*.docx,*.sys -ExclusionFile *New*,*au* -AdminOnly - Throttle 10 

この䟋では、コンピュヌタヌws-pc-4902、ws-pc-098、ファむル* File1 *、* File2 *を陀くすべおの拡匵子* .doc、*。Docx、*。Sysを持぀ファむルを怜玢したす。 レポヌトは管理者にのみ送信されたす。 スレッドの数は10です。

タヌゲットコンピュヌタヌの蚭定


OU  RemoteComputerの指定に必芁たたは必芁 -タヌゲットコンピュヌタヌのある組織単䜍ぞのパス。このパラメヌタヌが指定されおいない堎合、RemoteComputerパラメヌタヌを指定する必芁がありたす。 これらの2぀のパラメヌタヌのいずれかをスクリプトで䜿甚する必芁がありたす。

䟋-OU "OU =テスト、DC =ルヌト、DC =ロヌカル"たたは-OU $ Computerlist倉数は他のスクリプトず組み合わせお蚭定されたす。

RemoteComputer  OUの指定に必芁たたは必須 -リストの特定のコンピュヌタヌ特定の1぀たたは耇数のコンマに察しおのみスクリプトを実行する必芁がある堎合に蚭定

䟋-RemoteComputer ws-pc-4902、ws-pc-0982

怜玢オプション


IncludeFile  必須、マスクを䜿甚できたす *-怜玢する必芁があるファむルたたはその拡匵子のリストリストの堎合がありたす。

ExclusionFile  オプション -怜玢から陀倖するファむルのリストリストの堎合がありたす。

ExclusionFolder  オプション -怜玢から陀倖されたディレクトリのリスト。

レポヌトオプション


ReportPath  オプション -スキャン結果がコピヌされるネットワヌクリ゜ヌスたたはロヌカルディレクトリぞのパス。

AdminMail  オプション -レポヌトを送信するためのアドレス。管理者宛おのレポヌトは同じアドレスに配信されたす。

SMTP  オプション -メッセヌゞを送信するためのゲヌトりェむずしお䜿甚されるSMTPサヌバヌの名前。

AdminOnly  オプション -管理者のみにレポヌトを送信するモヌドを有効にしたす。

スロットル  必須、1〜99の数倀 -スキャンスレッドの数を蚭定したす。

モゞュヌルのむンストヌル


ファむルをディレクトリ「C\ Windows \ system32 \ WindowsPowerShell \ v1.0 \ Modules」にコピヌする必芁がありたす。
Invoke-Parallel.psm1
Start-AuditFiles.psm1

スクリプトを実行する前に、モゞュヌルをむンポヌトする必芁がありたす。

 Import-Module C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Invoke-Parallel.psm1 Import-Module C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Start-AuditFiles.psm1 

スクリプトモゞュヌル


このスクリプトは、 Invoke-Parallel.psm1ファむルずしお保存する必芁がありたす。

スクリプトInvoke-Parallel.psm1
 function Invoke-Parallel { [cmdletbinding(DefaultParameterSetName='ScriptBlock')] Param ( [Parameter(Mandatory=$false,position=0,ParameterSetName='ScriptBlock')] [System.Management.Automation.ScriptBlock]$ScriptBlock, [Parameter(Mandatory=$false,ParameterSetName='ScriptFile')] [ValidateScript({test-path $_ -pathtype leaf})] $ScriptFile, [Parameter(Mandatory=$true,ValueFromPipeline=$true)] [Alias('CN','__Server','IPAddress','Server','ComputerName')] [PSObject]$InputObject, [PSObject]$Parameter, [switch]$ImportVariables, [switch]$ImportModules, [int]$Throttle = 20, [int]$SleepTimer = 200, [int]$RunspaceTimeout = 0, [switch]$NoCloseOnTimeout = $false, [int]$MaxQueue, [validatescript({Test-Path (Split-Path $_ -parent)})] [string]$LogFile = "C:\temp\log.log", [switch] $Quiet = $false ) Begin { if( -not $PSBoundParameters.ContainsKey('MaxQueue') ) { if($RunspaceTimeout -ne 0){ $script:MaxQueue = $Throttle } else{ $script:MaxQueue = $Throttle * 3 } } else { $script:MaxQueue = $MaxQueue } Write-Verbose "Throttle: '$throttle' SleepTimer '$sleepTimer' runSpaceTimeout '$runspaceTimeout' maxQueue '$maxQueue' logFile '$logFile'" if ($ImportVariables -or $ImportModules) { $StandardUserEnv = [powershell]::Create().addscript({ $Modules = Get-Module | Select -ExpandProperty Name $Snapins = Get-PSSnapin | Select -ExpandProperty Name $Variables = Get-Variable | Select -ExpandProperty Name @{ Variables = $Variables Modules = $Modules Snapins = $Snapins } }).invoke()[0] if ($ImportVariables) { Function _temp {[cmdletbinding()] param() } $VariablesToExclude = @( (Get-Command _temp | Select -ExpandProperty parameters).Keys + $PSBoundParameters.Keys + $StandardUserEnv.Variables ) Write-Verbose "Excluding variables $( ($VariablesToExclude | sort ) -join ", ")" $UserVariables = @( Get-Variable | Where { -not ($VariablesToExclude -contains $_.Name) } ) Write-Verbose "Found variables to import: $( ($UserVariables | Select -expandproperty Name | Sort ) -join ", " | Out-String).`n" } if ($ImportModules) { $UserModules = @( Get-Module | Where {$StandardUserEnv.Modules -notcontains $_.Name -and (Test-Path $_.Path -ErrorAction SilentlyContinue)} | Select -ExpandProperty Path ) $UserSnapins = @( Get-PSSnapin | Select -ExpandProperty Name | Where {$StandardUserEnv.Snapins -notcontains $_ } ) } } Function Get-RunspaceData { [cmdletbinding()] param( [switch]$Wait ) Do { $more = $false if (-not $Quiet) { Write-Progress -Activity "Running Query" -Status "Starting threads"` -CurrentOperation "$startedCount threads defined - $totalCount input objects - $script:completedCount input objects processed"` -PercentComplete $( Try { $script:completedCount / $totalCount * 100 } Catch {0} ) } Foreach($runspace in $runspaces) { $currentdate = Get-Date $runtime = $currentdate - $runspace.startTime $runMin = [math]::Round( $runtime.totalminutes ,2 ) $log = "" | select Date, Action, Runtime, Status, Details $log.Action = "Removing:'$($runspace.object)'" $log.Date = $currentdate $log.Runtime = "$runMin minutes" If ($runspace.Runspace.isCompleted) { $script:completedCount++ if($runspace.powershell.Streams.Error.Count -gt 0) { $log.status = "CompletedWithErrors" Write-Verbose ($log | ConvertTo-Csv -Delimiter ";" -NoTypeInformation)[1] foreach($ErrorRecord in $runspace.powershell.Streams.Error) { Write-Error -ErrorRecord $ErrorRecord } } else { $log.status = "Completed" Write-Verbose ($log | ConvertTo-Csv -Delimiter ";" -NoTypeInformation)[1] } $runspace.powershell.EndInvoke($runspace.Runspace) $runspace.powershell.dispose() $runspace.Runspace = $null $runspace.powershell = $null } ElseIf ( $runspaceTimeout -ne 0 -and $runtime.totalseconds -gt $runspaceTimeout) { $script:completedCount++ $timedOutTasks = $true $log.status = "TimedOut" Write-Verbose ($log | ConvertTo-Csv -Delimiter ";" -NoTypeInformation)[1] Write-Error "Runspace timed out at $($runtime.totalseconds) seconds for the object:`n$($runspace.object | out-string)" if (!$noCloseOnTimeout) { $runspace.powershell.dispose() } $runspace.Runspace = $null $runspace.powershell = $null $completedCount++ } ElseIf ($runspace.Runspace -ne $null ) { $log = $null $more = $true } if($logFile -and $log){ ($log | ConvertTo-Csv -Delimiter ";" -NoTypeInformation)[1] | out-file $LogFile -append } } $temphash = $runspaces.clone() $temphash | Where { $_.runspace -eq $Null } | ForEach { $Runspaces.remove($_) } if($PSBoundParameters['Wait']){ Start-Sleep -milliseconds $SleepTimer } } while ($more -and $PSBoundParameters['Wait']) } if($PSCmdlet.ParameterSetName -eq 'ScriptFile') { $ScriptBlock = [scriptblock]::Create( $(Get-Content $ScriptFile | out-string) ) } elseif($PSCmdlet.ParameterSetName -eq 'ScriptBlock') { [string[]]$ParamsToAdd = '$_' if( $PSBoundParameters.ContainsKey('Parameter') ) { $ParamsToAdd += '$Parameter' } $UsingVariableData = $Null if($PSVersionTable.PSVersion.Major -gt 2) { $UsingVariables = $ScriptBlock.ast.FindAll({$args[0] -is [System.Management.Automation.Language.UsingExpressionAst]},$True) If ($UsingVariables) { $List = New-Object 'System.Collections.Generic.List`1[System.Management.Automation.Language.VariableExpressionAst]' ForEach ($Ast in $UsingVariables) { [void]$list.Add($Ast.SubExpression) } $UsingVar = $UsingVariables | Group SubExpression | ForEach {$_.Group | Select -First 1} $UsingVariableData = ForEach ($Var in $UsingVar) { Try { $Value = Get-Variable -Name $Var.SubExpression.VariablePath.UserPath -ErrorAction Stop [pscustomobject]@{ Name = $Var.SubExpression.Extent.Text Value = $Value.Value NewName = ('$__using_{0}' -f $Var.SubExpression.VariablePath.UserPath) NewVarName = ('__using_{0}' -f $Var.SubExpression.VariablePath.UserPath) } } Catch { Write-Error "$($Var.SubExpression.Extent.Text) is not a valid Using: variable!" } } $ParamsToAdd += $UsingVariableData | Select -ExpandProperty NewName -Unique $NewParams = $UsingVariableData.NewName -join ', ' $Tuple = [Tuple]::Create($list, $NewParams) $bindingFlags = [Reflection.BindingFlags]"Default,NonPublic,Instance" $GetWithInputHandlingForInvokeCommandImpl = ($ScriptBlock.ast.gettype().GetMethod('GetWithInputHandlingForInvokeCommandImpl',$bindingFlags)) $StringScriptBlock = $GetWithInputHandlingForInvokeCommandImpl.Invoke($ScriptBlock.ast,@($Tuple)) $ScriptBlock = [scriptblock]::Create($StringScriptBlock) Write-Verbose $StringScriptBlock } } $ScriptBlock = $ExecutionContext.InvokeCommand.NewScriptBlock("param($($ParamsToAdd -Join ", "))`r`n" + $Scriptblock.ToString()) } else { Throw "Must provide ScriptBlock or ScriptFile"; Break } Write-Debug "`$ScriptBlock: $($ScriptBlock | Out-String)" Write-Verbose "Creating runspace pool and session states" $sessionstate = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault() if ($ImportVariables) { if($UserVariables.count -gt 0) { foreach($Variable in $UserVariables) { $sessionstate.Variables.Add( (New-Object -TypeName System.Management.Automation.Runspaces.SessionStateVariableEntry -ArgumentList $Variable.Name, $Variable.Value, $null) ) } } } if ($ImportModules) { if($UserModules.count -gt 0) { foreach($ModulePath in $UserModules) { $sessionstate.ImportPSModule($ModulePath) } } if($UserSnapins.count -gt 0) { foreach($PSSnapin in $UserSnapins) { [void]$sessionstate.ImportPSSnapIn($PSSnapin, [ref]$null) } } } $runspacepool = [runspacefactory]::CreateRunspacePool(1, $Throttle, $sessionstate, $Host) $runspacepool.Open() Write-Verbose "Creating empty collection to hold runspace jobs" $Script:runspaces = New-Object System.Collections.ArrayList $bound = $PSBoundParameters.keys -contains "InputObject" if(-not $bound) { [System.Collections.ArrayList]$allObjects = @() } if( $LogFile ){ New-Item -ItemType file -path $logFile -force | Out-Null ("" | Select Date, Action, Runtime, Status, Details | ConvertTo-Csv -NoTypeInformation -Delimiter ";")[0] | Out-File $LogFile } $log = "" | Select Date, Action, Runtime, Status, Details $log.Date = Get-Date $log.Action = "Batch processing started" $log.Runtime = $null $log.Status = "Started" $log.Details = $null if($logFile) { ($log | convertto-csv -Delimiter ";" -NoTypeInformation)[1] | Out-File $LogFile -Append } $timedOutTasks = $false } Process { if($bound) { $allObjects = $InputObject } Else { [void]$allObjects.add( $InputObject ) } } End { Try { $totalCount = $allObjects.count $script:completedCount = 0 $startedCount = 0 foreach($object in $allObjects){ $powershell = [powershell]::Create() if ($VerbosePreference -eq 'Continue') { [void]$PowerShell.AddScript({$VerbosePreference = 'Continue'}) } [void]$PowerShell.AddScript($ScriptBlock).AddArgument($object) if ($parameter) { [void]$PowerShell.AddArgument($parameter) } if ($UsingVariableData) { Foreach($UsingVariable in $UsingVariableData) { Write-Verbose "Adding $($UsingVariable.Name) with value: $($UsingVariable.Value)" [void]$PowerShell.AddArgument($UsingVariable.Value) } } $powershell.RunspacePool = $runspacepool $temp = "" | Select-Object PowerShell, StartTime, object, Runspace $temp.PowerShell = $powershell $temp.StartTime = Get-Date $temp.object = $object $temp.Runspace = $powershell.BeginInvoke() $startedCount++ Write-Verbose ( "Adding {0} to collection at {1}" -f $temp.object, $temp.starttime.tostring() ) $runspaces.Add($temp) | Out-Null Get-RunspaceData $firstRun = $true while ($runspaces.count -ge $Script:MaxQueue) { if($firstRun){ Write-Verbose "$($runspaces.count) items running - exceeded $Script:MaxQueue limit." } $firstRun = $false Get-RunspaceData Start-Sleep -Milliseconds $sleepTimer } } Write-Verbose ( "Finish processing the remaining runspace jobs: {0}" -f ( @($runspaces | Where {$_.Runspace -ne $Null}).Count) ) Get-RunspaceData -wait if (-not $quiet) { Write-Progress -Activity "Running Query" -Status "Starting threads" -Completed } } Finally { if ( ($timedOutTasks -eq $false) -or ( ($timedOutTasks -eq $true) -and ($noCloseOnTimeout -eq $false) ) ) { Write-Verbose "Closing the runspace pool" $runspacepool.close() } [gc]::Collect() } } } 


次のスクリプトは、ファむルStart-AuditFiles.psm1ずしお保存する必芁がありたす。

スクリプトStart-AuditFiles.psm1
 $Body = ",              .     ,            .     : 1)         2)         . Function Start-AuditFiles { <# .Synopsis     ,        .Description            (C$ D$ ..  .).   : 1.      OU      2.    3.     4.      ,   5.    6.   ,    ,    7.    ,       .Examples  1 Start-AuditFiles -OU "OU=Test,DC=root,DC=local" -SMTP smtp.server.com -AdminMail administrator@server.com -IncludeFile *.doc,*.docx,*.sys -ExclusionFile *File1*,*File2* -ExclusionFolder *Folder1*,*Folder2* -ReportPath \\server\reports\         OU,     (*.doc,*.docx,*.sys)   (*File1*,*File2*),   (*Folder1*,*Folder2*),     (\\server\reports\)  2 Start-AuditFiles -RemoteComputer ws-pc-4902,ws-pc-0982 -SMTP smtp.server.com -AdminMail administrator@server.com -Include *.doc,*.docx,*.sys -ExclusionFile *New*,*au* -AdminOnly        (ws-pc-4902,ws-pc-098),     (*.doc,*.docx,*.sys)   (*File1*,*File2*),     .Notes       OU  RemoteComputer, OU   , RemoteComputer          .Link ... #> [CmdletBinding()] Param ( [String]$OU, [String[]]$RemoteComputer, [String[]]$ExclusionFile, [String]$ReportPath, [String]$AdminMail, [String[]]$IncludeFile, [String[]]$ExclusionFolder, [Switch]$AdminOnly = $false, [String]$SMTP, [String]$Throttle = 5 ) If (!$RemoteComputer) {$Hosts = (Get-ADComputer -Filter * -SearchBase $OU -Properties * | where { ( $PSItem.HomePage -notlike 'pass' )} ).name} else { $Hosts = $RemoteComputer } invoke-parallel -InputObject $Hosts -throttle $Throttle -ImportVariables -ScriptBlock { if(Test-Connection -ComputerName $_ -BufferSize 16 -quiet -count 2) { $Object = $_ $ErrorActionPreference = 'SilentlyContinue' $ExclusionFolder2 = $ExclusionFolder -replace ",","|" $StartTime = (Get-Date).ToString() $Hosts (Get-WMIObject Win32_LogicalDisk -filter "DriveType = 3" -ComputerName $Object | %{Get-ChildItem ('\\' + $Object + '\' + ($_.DeviceID).remove(1) + '$\*') -Include $IncludeFile -Exclude $ExclusionFile -Recurse -Force | ?{$PSItem.FullName -notmatch $ExclusionFolder2}}).FullName | Out-File -FilePath $env:TEMP\$Object.txt -Encoding unicode If (!$ReportPath) {} else {Copy-Item -Path $env:TEMP\$Object.txt -Destination $ReportPath -Force} $EndTime = (Get-Date).ToString() Write-Output ($Object) | Add-Content $env:TEMP\Online.txt Invoke-Item $env:TEMP\$Object.txt $Results = "" | Select ComputerName, "StartTime", "EndTime" $Results.ComputerName = $Object $Results.StartTime = $StartTime $Results.EndTime =$EndTime $Results If ((Get-Content $env:TEMP\$Object.txt) -eq $Null) {} else { Try { Send-MailMessage -SmtpServer $SMTP -to $AdminMail -Body $Object -From denis.pasternak@hotmail.com -Subject $Object -Attachments $env:TEMP\$Object.txt } Catch {''} If ($AdminOnly -eq $True) { Write-Host "  AdminOnly -    " -ForegroundColor Yellow} else { $Username=((gwmi win32_computersystem -computer $Object -ErrorAction SilentlyContinue).UserName -split '\\')[1] if($username -ne $null) { $Body = $Body $dispalyname = (Get-AdUser $username -properties DisplayName).DisplayName $email = (Get-AdUser $username -properties mail).mail sleep -Seconds 3 Send-MailMessage -SmtpServer $SMTP -Body ( ' ' + $Dispalyname + ' ' + $Body | out-string ) -To $email -From $AdminMail -Subject $Object -Attachments $env:TEMP\$Object.txt -Encoding Unicode } } } else{ } } else { (Write-Output ($Object + ' ' + (Get-Date).ToString()) | Add-Content $env:TEMP\Offline.txt)} } $OU= $null $RemoteComputer = $null $Hosts = $nul Get-Content $env:TEMP\Online.txt | Set-ADComputer -HomePage 'pass' } Function Remove-AuditFiles { [CmdletBinding(SupportsShouldProcess=$True)] Param ( [String]$TargetFile ) Get-Content -Path "$env:TEMP\$Path" | %{Remove-Item $PSItem} } Function Reset-AuditComputers { [CmdletBinding(SupportsShouldProcess=$True)] Param ( [String]$TargetOU ) Get-ADComputer -Filter * -SearchBase $TargetOU -Properties * | Set-ADComputer -HomePage 'notpass' '' | Set-Content -Path $env:TEMP\Online.txt } 


スケゞュヌルされた実行


サンプルディレクトリc\ scriptsにファむルを䜜成したす。

RunScript.ps1-ファむル

テキストをコピヌしたす。

 Import-Module C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Invoke-Parallel.psm1 Import-Module C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Start-AuditFiles.psm1 #   ,       Start-AuditFiles -OU "OU=Test,DC=root,DC=local" -SMTP smtp.server.com -AdminMail administrator@server.com -IncludeFile *.doc,*.docx,*.sys -ExclusionFile *File1*,*File2* -ExclusionFolder *Folder1*,*Folder2* -ReportPath \\server\reports\ - Throttle 5 

ファむル怜玢スケゞュヌルを䜜成する



結果ず䜜業ファむルに関する情報


スクリプトは、スキャン結果をTEMPディレクトリに保存したす。 䟋では、このディレクトリはC\ Users \ Administrator \ AppData \ Local \ Tempです。 コンピュヌタヌが䜿甚可胜で、ファむルが芋぀かった堎合、結果を含むファむルが䜜成されたす。 コンピュヌタヌが䜿甚できない堎合、これに関する情報がoffline.txtファむルに远加されたす。



芋぀かったファむルを削陀する


PowerShellを起動しおコマンドを実行したす。

 Import-Module C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Start-AuditFiles.psm1 Remove-AuditFiles  Remove-AuditFiles - TargetFile ws-9281.txt,ws-8721.txt 

Remove-AuditFiles-すべおの怜玢結果を怜玢し、各結果を凊理した埌、ファむルを削陀したす。

特定のファむル特定のコンピュヌタヌを指定できたす。䟋

Remove-AuditFiles-TargetFile ws-9281.txt、ws-8721.txt

スキャンしたコンピュヌタヌのリストをリセットする


PowerShellを起動しおコマンドを実行したす。

Reset-AuditComputers

実行埌、指定されたOUのコンピュヌタヌはスキャンされおいないものずしおマヌクされたす。

 Import-Module C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Start-AuditFiles.psm1 Reset-AuditComputers - TargetOU OU "OU=Test,DC=root,DC=local" 

スクリプトの説明
$ Body倉数-メッセヌゞの本文に挿入されるテキストが含たれたす。 将来、このテキストぱンドナヌザヌに手玙で送られたす。

 $Body = ",              .     ,            .     : 1)         2)         . 

掟生名Start-AuditFilesが䞎えられた関数の始たり

 Function Start-AuditFiles { 

ヘルプテキストを䌎うスクリプトの説明。 「Get-Help Start-AuditFiles」を䜿甚しお、ヘルプを䜿甚し、䟋ず構文に関する情報を取埗できたす。

 <# .Synopsis     ,        .Description            (C$ D$ ..  .).   : 1.      OU      2.    3.     4.      ,   5.    6.   ,    ,    7.    ,       .Examples  1 Start-AuditFiles -OU "OU=Test,DC=root,DC=local" -SMTP smtp.server.com -AdminMail administrator@server.com -IncludeFile *.doc,*.docx,*.sys -ExclusionFile *File1*,*File2* -ExclusionFolder *Folder1*,*Folder2* -ReportPath \\server\reports\         OU,     (*.doc,*.docx,*.sys)   (*File1*,*File2*),   (*Folder1*,*Folder2*),     (\\server\reports\)  2 Start-AuditFiles -RemoteComputer ws-pc-4902,ws-pc-0982 -SMTP smtp.server.com -AdminMail administrator@server.com -Include *.doc,*.docx,*.sys -ExclusionFile *New*,*au* -AdminOnly        (ws-pc-4902,ws-pc-098),     (*.doc,*.docx,*.sys)   (*File1*,*File2*),     .Notes       OU  RemoteComputer, OU   , RemoteComputer          .Link ... #> 

関数で将来䜿甚する倉数に぀いお説明したす。

$ OU-Active Directoryの組織単䜍ぞのパス
$ ExclusionFile-怜玢から陀倖されたファむルのリスト
$ ReportPath-レポヌトが耇補されるディレクトリぞのパス
$ AdminMail-レポヌトの送信元および管理者向けのコピヌの送信元の管理者の電子メヌルアドレス
$ IncludeFile-怜玢されるファむル拡匵子たたはファむル名
$ ExclusionFolder-怜玢から陀倖されたフォルダヌのリスト
$ AdminOnly-レポヌトを管理者のみに送信するかどうかを回答するパラメヌタヌ
$ SMTP-SMTPサヌバヌのアドレスたたは名前
$スロットル-䞊列スレッドの数。

 [CmdletBinding()] Param ( [String]$OU, [String[]]$RemoteComputer, [String[]]$ExclusionFile, [String]$ReportPath, [String]$AdminMail, [String[]]$IncludeFile, [String[]]$ExclusionFolder, [Switch]$AdminOnly = $false, [String]$SMTP, [String]$Throttle = 5 ) 

「RemoteComputer」キヌが䜿甚された堎合、チェックが実行されたす。この堎合、スキャンは特定の指定されたコンピュヌタヌでのみ行われ、「OU」キヌが指定された堎合-この堎合リストは指定されたOU ADから取埗され、HomePage属性を持぀コンピュヌタヌが遞択されたす「パス」これは、既に怜玢されたマシンで怜玢が繰り返されるのを防ぐために行われたす。

 If (!$RemoteComputer) {$Hosts = (Get-ADComputer -Filter * -SearchBase $OU -Properties * | where { ( $PSItem.HomePage -notlike 'pass' )} ).name} else { $Hosts = $RemoteComputer } 

スクリプト実行の開始、ホスト倀、およびスレッド数が眮き換えられたす。

 invoke-parallel -InputObject $Hosts -throttle $Throttle -ImportVariables -ScriptBlock { 

ネットワヌク䞊のコンピュヌタヌの可甚性を確認したす。

 if(Test-Connection -ComputerName $_ -BufferSize 16 -quiet -count 2) { 

怜玢の実行に必芁な倉数の倀は、䞊蚘の倉数から取埗されたす。 怜玢の開始は蚘憶されたす。

  $Object = $_ $ErrorActionPreference = 'SilentlyContinue' $ExclusionFolder2 = $ExclusionFolder -replace ",","|" $StartTime = (Get-Date).ToString() $Hosts 

怜玢の実行

  • 物理ディスクのリストの取埗Get-WMIObject Win32_LogicalDisk -filter "DriveType = 3" -ComputerName $ Object
  • UNCパスはドラむブ文字Get-ChildItem '\\' + $ Object + '\' +$ _。DeviceID.remove1+ '$ \ *'で圢成されたす
  • 含たれるオブゞェクトず陀倖の怜玢のキヌを瀺したす-Include $ IncludeFile -Exclude $ ExclusionFile -Recurse -Force
  • , (?{$PSItem.FullName -notmatch $ExclusionFolder2}}).FullName)
  • (Out-File -FilePath $env:TEMP$Object.txt -Encoding unicode)

 (Get-WMIObject Win32_LogicalDisk -filter "DriveType = 3" -ComputerName $Object | %{Get-ChildItem ('\\' + $Object + '\' + ($_.DeviceID).remove(1) + '$\*') -Include $IncludeFile -Exclude $ExclusionFile -Recurse -Force | ?{$PSItem.FullName -notmatch $ExclusionFolder2}}).FullName | Out-File -FilePath $env:TEMP\$Object.txt -Encoding unicode 

, «ReportPath», .
  If (!$ReportPath) {} else {Copy-Item -Path $env:TEMP\$Object.txt -Destination $ReportPath -Force} 

.

  $EndTime = (Get-Date).ToString() 

, .

 Write-Output ($Object) | Add-Content $env:TEMP\Online.txt 

, , .

  Invoke-Item $env:TEMP\$Object.txt $Results = "" | Select ComputerName, "StartTime", "EndTime" $Results.ComputerName = $Object $Results.StartTime = $StartTime $Results.EndTime =$EndTime $Results 

, , ( ), . .

 If ((Get-Content $env:TEMP\$Object.txt) -eq $Null) {} 

, SMTP , , , .

  else { Try { Send-MailMessage -SmtpServer $SMTP -to $AdminMail -Body $Object -From denis.pasternak@hotmail.com -Subject $Object -Attachments $env:TEMP\$Object.txt } Catch {''} 

, , .

 If ($AdminOnly -eq $True) { Write-Host "  AdminOnly -    " -ForegroundColor Yellow} else 

.

 { $Username=((gwmi win32_computersystem -computer $Object -ErrorAction SilentlyContinue).UserName -split '\\')[1] if($username -ne $null) 

, Active Directory, Email. Active Directory.

  { $Body = $Body $dispalyname = (Get-AdUser $username -properties DisplayName).DisplayName $email = (Get-AdUser $username -properties mail).mail sleep -Seconds 3 

, $Body Active Directory.

 Send-MailMessage -SmtpServer $SMTP -Body ( ' ' + $Dispalyname + ' ' + $Body | out-string ) -To $email -From $AdminMail -Subject $Object -Attachments $env:TEMP\$Object.txt -Encoding Unicode 

, , .

  } } } else{ } } else { (Write-Output ($Object + ' ' + (Get-Date).ToString()) | Add-Content $env:TEMP\Offline.txt)} } 

.

 $OU= $null $RemoteComputer = $null $Hosts = $nul 

«HomePage» Active Directory. , .

 Get-Content $env:TEMP\Online.txt | Set-ADComputer -HomePage 'pass' } 

, , ( ), . $TargetFile – .

 Function Remove-AuditFiles { [CmdletBinding(SupportsShouldProcess=$True)] Param ( [String]$TargetFile ) Get-Content -Path "$env:TEMP\$Path" | %{Remove-Item $PSItem} } 

HomePage Active Directory. OU. -.

 Function Reset-AuditComputers { [CmdletBinding(SupportsShouldProcess=$True)] Param ( [String]$TargetOU ) Get-ADComputer -Filter * -SearchBase $TargetOU -Properties * | Set-ADComputer -HomePage 'notpass' '' | Set-Content -Path $env:TEMP\Online.txt } 

Source: https://habr.com/ru/post/J275035/


All Articles