- PVSM.RU - https://www.pvsm.ru -

Процедура блокировки учетных записей пользователей

Данный скрипт ни что иное, как процедура блокировки пользователя, попрощавшегося с компанией.
Допустим у нас в компании согласована следующая процедура действий при увольнении сотрудника:
— Аккаунт пользователя необходимо блокировать вместе с почтовым ящиком.
— Всю почту сотрудника необходимо выгружать в pst файл в какой-нибудь файловый архив.
— Необходимо предотвратить любую возможносмть удаленного доступа к коропративной сети.
— Заблокированные аккаунты необходимо перемещать из продакшн контейнера в какой-нибудь отстойник для последующего удаления через какое-то время.

Вот всем этим и займемся…

Небольшие дополнения к условиям задачи, взятые из конкретной ситуации:
— VPN предоставлен посредством дополнения пользователей в определенные VPN* группы безопасности.
— Контейнеры с аккаунтами пользователей разбиты по странам и в каждой находится подконтейнер Disabled, куда и перемещаются заблокированные аккаунты.

Скрипт выглядит так:

#
#    A user disabling procedure.
#    Prepared by Alexander Lipovetskiy 30.09.2013.
#    Version 1.00
#

cls

# Load required modules

if (-not (Get-Module ActiveDirectory))
    {
    Write-Host "Please wait while script imports all necessary modules..."
    Add-PSSnapin Microsoft.Exchange* -WarningAction SilentlyContinue
    Set-ADServerSettings -ViewEntireForest:$True -WarningAction SilentlyContinue
    Import-Module ActiveDirectory -WarningAction SilentlyContinue
    Write-Host "All modules have been loaded."
    }

# Variables

$Leaver = Read-Host `n"Enter an account name to disable"
$Country = Get-ADUser $Leaver -Properties Country | select Country -ExpandProperty Country
$FilePath = "\ServerMailbox_share$Country$Leaver.pst"
$Date = get-date -Format g
$ITstaff = whoami
$Logs = "d:ScriptsUserDisablingLogs"

# Disable user account

try
    {
    Disable-ADAccount $Leaver
    Set-ADUser $Leaver -Description "Leaver, disabled by $ITstaff on $Date"
    Write-Host "$Date The account $Leaver has been disabled." -ForegroundColor Yellow
    Write-Output "$Date The account $Leaver has been disabled." | Out-File -FilePath "$Logs$Leaver.txt" -Append
    }

catch
    {
    Write-Host "$Leaver does not exist or you have not enough permissions to disable it." -ForegroundColor Red
    exit
    }

# Remove VPN Access

Write-Host "Removing $Leaver from VPN groups..."

Get-ADGroup -Filter {Name -like "VPN*"} | ForEach-Object 
    {
    $_ = $_.Name
    try
        {
        Remove-ADGroupMember -Confirm:$False -Identity $_ -Members $Leaver
        Write-Host "$Leaver has been removed from group $_" -ForegroundColor Yellow
        Write-Output "$Leaver has been removed from group $_" | Out-File -FilePath "$Logs$Leaver.txt" -Append
        } 
    catch {}
    }

Write-Host "Removing of $Leaver from VPN groups completed."

# Move account into a Disabled OU

Write-Host "Moving $Leaver into a Disabled OU..."

$DN = Get-ADUser $Leaver | Select DistinguishedName -ExpandProperty DistinguishedName

$DisabledOU = $DN -replace "CN=$Leaver","OU=Disabled"

try
    {
    Move-ADObject -Identity $DN -TargetPath $DisabledOU -Confirm:$false
    Write-Host "$Leaver has been moved into $DisabledOU." -ForegroundColor Yellow
    Write-Output "$Leaver has been moved into $DisabledOU." | Out-File -FilePath "$Logs$Leaver.txt" -Append
    }

catch
    {
    Write-Host "Disabled OU does not exist or $Leaver is already there." -ForegroundColor Red
    Write-Output "Disabled OU does not exist or $Leaver is already there." | Out-File -FilePath "$Logs$Leaver.txt" -Append
    }

# Mailbox export

Write-Host "Exporting mailbox of $Leaver..."

New-MailboxExportRequest -Mailbox $Leaver -Name $Leaver -FilePath $FilePath -confirm:$false -WarningAction SilentlyContinue

$Stat = Get-MailboxExportRequest | where {$_.Name -eq $Leaver} | Get-MailboxExportRequestStatistics
$Status = $Stat.Status 

while (($Status -eq "Queued") -or ($Status -eq "InProgress"))
    {
    $Stat = Get-MailboxExportRequest | where {$_.Name -eq $Leaver} | Get-MailboxExportRequestStatistics
    $Status = $Stat.Status
    $PercentComplete = $Stat.PercentComplete
    $BytesTransferred = $Stat.BytesTransferred
    if ($PercentComplete -eq "") {$PercentComplete = 0}
    else {$PercentComplete = $Stat.PercentComplete}
    Write-Host `n"Archiving status is:" $Status
    Write-Host "Percent complete:" $PercentComplete
    Write-Host "Bytes transferred:" $BytesTransferred
    Write-Progress -Activity "Creating archive... $PercentComplete % completed" -PercentComplete $PercentComplete -Status "Processing the archive of $Leaver."
    Start-Sleep -s 30
    }

$Stat = Get-MailboxExportRequest | where {$_.Name -eq $Leaver}  | Get-MailboxExportRequestStatistics -IncludeReport
$ExportLog = $Stat.Report
$ExportLog | Out-File -FilePath "$Logs$Leaver.txt" -Append

if ($Stat.Status -eq "Completed")
    {
    Write-Host `n"Mailbox of $Leaver has been exported into $FilePath." -ForegroundColor Yellow
    Write-Output "Mailbox of $Leaver has been exported into $FilePath." | Out-File -FilePath "$Logs$Leaver.txt" -Append
    }

else
    {
    Write-Host `n"Mailbox export of $Leaver FAILED." -ForegroundColor Red
    Write-Output "Mailbox export of $Leaver FAILED." | Out-File -FilePath "$Logs$Leaver.txt" -Append
    }

Get-MailboxExportRequest | where {$_.Name -eq $Leaver} | Remove-MailboxExportRequest -Confirm:$false -WarningAction SilentlyContinue

# The End

Write-Host `n"$Date User disabling procedure for $Leaver was successfully completed." -ForegroundColor Yellow
Write-Output `n"$Date User disabling procedure for $Leaver was successfully completed." | Out-File -FilePath "$Logs$Leaver.txt" –Append

Для того, чтобы с этим скриптом могли работать простые смертные из первой линии поддержки создадим для них группу “DomainExchange-ImportExport”, добавим туда необходимые аккаунты и присвоим этой группе необходимую роль в Exchange:

New-ManagementRoleAssignment -Name "Helpdesk Mailbox Import Export" –Role "Mailbox Import Export" –SecurityGroup “DomainExchange-ImportExport”

Вот как бы и все, но я расширю этот пост еще одной задачей от секьюрити менеджера: удалять все аккаунты, которые были заблокированы более 90 дней назад и только те, что лежат в наших Disabled отстойниках (то, что вне удалять нельзя).

Создаем следующий скрипт и закидываем его в планировщик для отработки каждую ночь на каком-нибудь менеджмент сервере:

#
# This script looks for disabled user accounts and deletes those which have date modified earlier than 90 days.
# Prepared by Alexander Lipovetskiy 30.09.2013.
# Version 1.00
#

# Let's load AD module

if (-not (Get-Module ActiveDirectory)){Import-Module ActiveDirectory}

# Variables

$Date = Get-Date -Format g
$DateToDelete = (Get-Date).AddDays(-90)
$Path = "OU=Accounts,DC=domain,DC=com"
$Log = "d:ScriptsUserDeletionDeleted_Users.txt"
$DisabledUsersToDelete = @()

# We process only user containers named Disabled

$OUs = Get-ADOrganizationalUnit -Filter * -SearchBase $Path | where {$_.DistinguishedName -like "*disabled*"}

# Filter out old disabled accounts

$OUs | ForEach-Object {
    $DisabledUsersToDelete += Get-ADUser -Filter {Enabled -eq $false} -SearchBase $_ -Properties Enabled, Modified | where {$_.Modified -le $DateToDelete}
    }

# Let's count them

$Count = $DisabledUsersToDelete.Count

# The accounts deletion.
# Achtung! The below deletes all gathered accounts, so, be careful!

Write-Output `n "$Date $Count disabled user accounts are going to be deleted." | Out-File -FilePath $Log -Append

$DisabledUsersToDelete | Remove-ADUser 

Write-Output `n "$Date User accounts from below have been deleted." | Out-File -FilePath $Log -Append
Write-Output `n $DisabledUsersToDelete.DistinguishedName | Out-File -FilePath $Log –Append

The End.

Автор: alex_at

Источник [1]


Сайт-источник PVSM.RU: https://www.pvsm.ru

Путь до страницы источника: https://www.pvsm.ru/powershell/44603

Ссылки в тексте:

[1] Источник: http://habrahabr.ru/post/195768/