Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Auteur: Alexis Ménard
- #Date: 2018-09-20
- #Sypnosis: Ce script est exécuté automatiquement par le Task Scheduler à toutes les minutes. Il répond automatiquement à tous courriel envoyés vers la boîte de l'utilisateur DEPT-INFO\reset
- #Il génére compare d'abord l'adresse courriel de source pour trouver une correspondance dans AD. Si non, il avise le courriel source et l'utilisateur DEPT_INFO\logpass de l'échec de la recherche.
- #Ensuite il vérifie si le token fourni dans le courriel, si fourni, correspond à celui entré dans l'attribut "EmployeeID". Si non, il en génére un aléatoirement de 6 chiffres et l'envoi à l'adresse de l'utilisateur trouvé.
- #Pour terminer, si les deux première conditions sont satisfaites, que l'utilisateur a envoyé le bon token dans le "body" du courriel, le script génére un mot de passe aléatoire (voir fonction Create-RandomString), change le mot de passe de l'utilisateur
- #correspondant et envoi un courriel à ce dernier à son adresse personnelle et au compte DEPT-INFO\logpass
- #Déclaration des variables
- #Configuration block
- $SmtpServer = "......"
- $ResetEmail = "reset@......"
- $Username = "....\reset"
- $Password = "XXXXXXXX"
- $MailServer = "......."
- $ExchangeVersion = "Exchange2013"
- #Field containing the comparaison attribute
- $ADMailField = "Office"
- #Field containing the destination AD server
- $ADServer = "watson"
- #User who shold recieve email notifications that a password was reset or an invalid request/token was sent.
- $LoggingUser = "logpass@dept-info.crosemont.quebec"
- #Download for the subsequent file is here: https://www.microsoft.com/en-ca/download/details.aspx?id=42951
- #Lien vers le téléchargement du fichier ci-dessous
- [Reflection.Assembly]::LoadFile("C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll")
- #Random generated password function
- #Fonction de génération aléatoire d'un mot de passe
- #Entre 8 et 10 caractères ($aChars)
- function Create-RandomString()
- {
- $aChars = @()
- $aChars = "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "C", "b", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "2", "3", "4", "5", "6", "7", "8", "9", "_", ";"
- $intUpperLimit = Get-Random -minimum 8 -maximum 10
- $x = 0
- $strString = ""
- while ($x -lt $intUpperLimit)
- {
- $a = Get-Random -minimum 0 -maximum $aChars.getupperbound(0)
- $strString += $aChars[$a]
- $x += 1
- }
- return $strString
- }
- #Random generated token function
- #Fonction de génération aléatoire d'un jeton
- #6 caractères ($aChars)
- function Create-RandomToken()
- {
- $aChars = @()
- $aChars = "1", "2", "3", "4", "5", "6", "7", "8", "9"
- $intUpperLimit = 6
- $x = 0
- $strString = ""
- while ($x -lt $intUpperLimit)
- {
- $a = Get-Random -minimum 0 -maximum $aChars.getupperbound(0)
- $strString += $aChars[$a]
- $x += 1
- }
- return $strString
- }
- #Connection au compte courriel de ....\reset
- $email = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::$ExchangeVersion)
- $email.Credentials = New-Object Net.NetworkCredential($Username, $Password)
- $uri=[system.URI] $MailServer
- $email.Url = $uri
- $inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($email,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)
- #Vérification de la présence de courriels non-lus
- if ($inbox.UnreadCount -gt 0)
- {
- $PropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
- $PropertySet.RequestedBodyType = [Microsoft.Exchange.WebServices.Data.BodyType]::Text;
- # Set search criteria - unread only
- $SearchForUnRead = New-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::IsRead, $false)
- $items = $inbox.FindItems($SearchForUnRead,10) #return only 10 unread mail items
- Import-Module -Name ActiveDirectory
- foreach ($item in $items.Items)
- {
- # load the property set to allow us to view the body
- $item.load($PropertySet)
- if($item.Body.text -Like "*")
- {
- #La section ci-dessous en commentaire permettra le fonctionnent par SMS si Vidéotron fini par le permettre
- #$Phone = $item.From.address
- #$Phone = $item.From.address.substring(0, $Phone.IndexOf("@"))
- #$user = Get-ADUser -Filter {MobilePhone -eq $phone} -Properties MobilePhone
- $EmailAddress = $item.From.address
- $user = Get-ADUser -Filter {$ADMailField -eq $EmailAddress} -Properties $ADMailField -Server $ADServer
- $fullName = $($user.DistinguishedName -split ",*..=")[1]
- $firstName = $($fullName -split " ")[0]
- $lastName = $($fullName -split " ")[1]
- #Retrieves the token stored in the "EmployeeID" attribute
- #Récupération du jeton sauvegardé dans l'attribut "EmployeeID"
- $tokenAD = $(Get-ADUser -Identity $user.SamAccountName -Properties EmployeeID -Server $ADServer | Select EmployeeID)
- $tokenAD = $tokenAD -split "="
- $tokenAD = $tokenAD[1] -replace "}",""
- #Retrieves the token sent in the email
- #Récupération du jeton envoyé dans le courriel
- $tokenMail = $item.Body.text -replace '\s',''
- If ($user -ne $null)
- {
- If ("$tokenAD" -like "$tokenMail")
- {
- $PW = Create-RandomString
- if ($PW.length -gt 1)
- {
- Set-ADAccountPassword -identity $user.samaccountname -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $PW -Force)
- Unlock-ADAccount -identity $user.samaccountname
- $PasswordAge = (Get-ADUser $user -Properties PasswordLastSet | Select PasswordLastSet)
- if ($PasswordAge.PasswordLastSet -ge (Get-Date).AddMinutes(-1)){
- $Body = "Bonjour $firstName $lastName. `r`n"
- $Body += "Votre nouveau mot de passe est : $PW"
- $BodyLog = "Password reset for $firstName $lastName `r`n"
- $BodyLog += "$user.DistinguishedName"
- send-mailmessage -to $LoggingUser -from $ResetEmail -subject "Password Reset - $firstName $lastName" -body $BodyLog -SmtpServer $SmtpServer
- send-mailmessage -to $item.From.address -from $ResetEmail -subject "Nouveau mot de passe Dept-Info" -body $Body -SmtpServer $SmtpServer
- }
- }
- }
- Else
- {
- $newToken = Create-RandomToken
- Set-ADUser -Identity $user.samaccountname -Replace @{EmployeeID="$newToken"} -Server $ADServer
- $Body = "Le jeton dans votre courriel est invalide. Votre nouveau jeton est : $newToken `r`n"
- $Body += "Veuillez entrer seulement ce jeton comme texte dans le contenu de votre prochain courriel pour recevoir un nouveau mot de passe pour votre compte departemental. `r`n"
- $Body += "Veuillez contacter votre administrateur si vos problemes de connexion persistent."
- $BodyLog = "A wrong token has been entered by an email linked to user $firstName $lastName."
- send-mailmessage -to $LoggingUser -from $ResetEmail -subject $BodyLog -body $BodyLog -SmtpServer $SmtpServer
- send-mailmessage -to $item.From.address -from $ResetEmail -subject "Jeton invalide" -body $Body -SmtpServer $SmtpServer
- }
- }
- else
- {
- send-mailmessage -to $LoggingUser -from $ResetEmail -subject "Adresse courriel invalide" -body "L'adresse courriel $EmailAddress n'a pas ete trouvee." -SmtpServer $SmtpServer
- send-mailmessage -to $item.From.address -from $ResetEmail -subject " " -body "L'adresse courriel $EmailAddress n'a pas ete trouvee, veuillez vous assurer d'utiliser l'adresse fournie au College lors de votre inscription." -SmtpServer $SmtpServer
- }
- }
- $item.Isread = $true
- $item.Update([Microsoft.Exchange.WebServices.Data.ConflictResolutionMode]::AlwaysOverwrite)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement