Advertisement
Guest User

Untitled

a guest
Sep 21st, 2018
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.74 KB | None | 0 0
  1. #Auteur: Alexis Ménard
  2. #Date: 2018-09-20
  3. #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
  4. #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.
  5. #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é.
  6. #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
  7. #correspondant et envoi un courriel à ce dernier à son adresse personnelle et au compte DEPT-INFO\logpass
  8.  
  9. #Déclaration des variables
  10. #Configuration block
  11. $SmtpServer = "......"
  12. $ResetEmail = "reset@......"
  13. $Username = "....\reset"
  14. $Password = "XXXXXXXX"
  15. $MailServer = "......."
  16. $ExchangeVersion = "Exchange2013"
  17.  
  18. #Field containing the comparaison attribute
  19. $ADMailField = "Office"
  20.  
  21. #Field containing the destination AD server
  22. $ADServer = "watson"
  23.  
  24. #User who shold recieve email notifications that a password was reset or an invalid request/token was sent.
  25. $LoggingUser = "logpass@dept-info.crosemont.quebec"
  26.  
  27. #Download for the subsequent file is here: https://www.microsoft.com/en-ca/download/details.aspx?id=42951
  28. #Lien vers le téléchargement du fichier ci-dessous
  29. [Reflection.Assembly]::LoadFile("C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll")
  30.  
  31.  
  32. #Random generated password function
  33. #Fonction de génération aléatoire d'un mot de passe
  34. #Entre 8 et 10 caractères ($aChars)
  35. function Create-RandomString()
  36. {
  37. $aChars = @()
  38. $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", "_", ";"
  39. $intUpperLimit = Get-Random -minimum 8 -maximum 10
  40.  
  41. $x = 0
  42. $strString = ""
  43. while ($x -lt $intUpperLimit)
  44. {
  45. $a = Get-Random -minimum 0 -maximum $aChars.getupperbound(0)
  46. $strString += $aChars[$a]
  47. $x += 1
  48. }
  49.  
  50. return $strString
  51. }
  52.  
  53.  
  54. #Random generated token function
  55. #Fonction de génération aléatoire d'un jeton
  56. #6 caractères ($aChars)
  57. function Create-RandomToken()
  58. {
  59. $aChars = @()
  60. $aChars = "1", "2", "3", "4", "5", "6", "7", "8", "9"
  61. $intUpperLimit = 6
  62.  
  63. $x = 0
  64. $strString = ""
  65. while ($x -lt $intUpperLimit)
  66. {
  67. $a = Get-Random -minimum 0 -maximum $aChars.getupperbound(0)
  68. $strString += $aChars[$a]
  69. $x += 1
  70. }
  71.  
  72. return $strString
  73. }
  74.  
  75. #Connection au compte courriel de ....\reset
  76. $email = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::$ExchangeVersion)
  77. $email.Credentials = New-Object Net.NetworkCredential($Username, $Password)
  78. $uri=[system.URI] $MailServer
  79. $email.Url = $uri
  80. $inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($email,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)
  81.  
  82. #Vérification de la présence de courriels non-lus
  83. if ($inbox.UnreadCount -gt 0)
  84. {
  85. $PropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
  86. $PropertySet.RequestedBodyType = [Microsoft.Exchange.WebServices.Data.BodyType]::Text;
  87. # Set search criteria - unread only
  88. $SearchForUnRead = New-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::IsRead, $false)
  89. $items = $inbox.FindItems($SearchForUnRead,10) #return only 10 unread mail items
  90.  
  91. Import-Module -Name ActiveDirectory
  92.  
  93. foreach ($item in $items.Items)
  94. {
  95. # load the property set to allow us to view the body
  96. $item.load($PropertySet)
  97.  
  98. if($item.Body.text -Like "*")
  99. {
  100. #La section ci-dessous en commentaire permettra le fonctionnent par SMS si Vidéotron fini par le permettre
  101. #$Phone = $item.From.address
  102. #$Phone = $item.From.address.substring(0, $Phone.IndexOf("@"))
  103. #$user = Get-ADUser -Filter {MobilePhone -eq $phone} -Properties MobilePhone
  104. $EmailAddress = $item.From.address
  105. $user = Get-ADUser -Filter {$ADMailField -eq $EmailAddress} -Properties $ADMailField -Server $ADServer
  106. $fullName = $($user.DistinguishedName -split ",*..=")[1]
  107. $firstName = $($fullName -split " ")[0]
  108. $lastName = $($fullName -split " ")[1]
  109. #Retrieves the token stored in the "EmployeeID" attribute
  110. #Récupération du jeton sauvegardé dans l'attribut "EmployeeID"
  111. $tokenAD = $(Get-ADUser -Identity $user.SamAccountName -Properties EmployeeID -Server $ADServer | Select EmployeeID)
  112. $tokenAD = $tokenAD -split "="
  113. $tokenAD = $tokenAD[1] -replace "}",""
  114. #Retrieves the token sent in the email
  115. #Récupération du jeton envoyé dans le courriel
  116. $tokenMail = $item.Body.text -replace '\s',''
  117.  
  118.  
  119. If ($user -ne $null)
  120. {
  121. If ("$tokenAD" -like "$tokenMail")
  122. {
  123. $PW = Create-RandomString
  124. if ($PW.length -gt 1)
  125. {
  126. Set-ADAccountPassword -identity $user.samaccountname -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $PW -Force)
  127. Unlock-ADAccount -identity $user.samaccountname
  128.  
  129. $PasswordAge = (Get-ADUser $user -Properties PasswordLastSet | Select PasswordLastSet)
  130. if ($PasswordAge.PasswordLastSet -ge (Get-Date).AddMinutes(-1)){
  131. $Body = "Bonjour $firstName $lastName. `r`n"
  132. $Body += "Votre nouveau mot de passe est : $PW"
  133. $BodyLog = "Password reset for $firstName $lastName `r`n"
  134. $BodyLog += "$user.DistinguishedName"
  135. send-mailmessage -to $LoggingUser -from $ResetEmail -subject "Password Reset - $firstName $lastName" -body $BodyLog -SmtpServer $SmtpServer
  136. send-mailmessage -to $item.From.address -from $ResetEmail -subject "Nouveau mot de passe Dept-Info" -body $Body -SmtpServer $SmtpServer
  137. }
  138. }
  139.  
  140. }
  141. Else
  142. {
  143. $newToken = Create-RandomToken
  144. Set-ADUser -Identity $user.samaccountname -Replace @{EmployeeID="$newToken"} -Server $ADServer
  145. $Body = "Le jeton dans votre courriel est invalide. Votre nouveau jeton est : $newToken `r`n"
  146. $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"
  147. $Body += "Veuillez contacter votre administrateur si vos problemes de connexion persistent."
  148. $BodyLog = "A wrong token has been entered by an email linked to user $firstName $lastName."
  149. send-mailmessage -to $LoggingUser -from $ResetEmail -subject $BodyLog -body $BodyLog -SmtpServer $SmtpServer
  150. send-mailmessage -to $item.From.address -from $ResetEmail -subject "Jeton invalide" -body $Body -SmtpServer $SmtpServer
  151. }
  152.  
  153. }
  154. else
  155. {
  156. send-mailmessage -to $LoggingUser -from $ResetEmail -subject "Adresse courriel invalide" -body "L'adresse courriel $EmailAddress n'a pas ete trouvee." -SmtpServer $SmtpServer
  157. 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
  158. }
  159. }
  160. $item.Isread = $true
  161. $item.Update([Microsoft.Exchange.WebServices.Data.ConflictResolutionMode]::AlwaysOverwrite)
  162. }
  163. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement