Компьютерный форум OSzone.net  

Компьютерный форум OSzone.net (http://forum.oszone.net/index.php)
-   Скриптовые языки администрирования Windows (http://forum.oszone.net/forumdisplay.php?f=102)
-   -   Отправка почты SSL через powershell (прошу доработать скрипт) (http://forum.oszone.net/showthread.php?t=333872)

android63rus 21-03-2018 06:08 2804566

Отправка почты SSL через powershell (прошу доработать скрипт)
 
Имеется небезысвестный скрипт отправки уведомления о смене пароля

Код:

Import-Module ActiveDirectory

#System globalization
#$ci = New-Object System.Globalization.CultureInfo("ru-RU")

#SMTP server name
$smtpServer = "mail.domain.local"

#Creating a Mail object
$msg = new-object Net.Mail.MailMessage
#Creating a Mail object for report
$msgr = new-object Net.Mail.MailMessage

#Creating SMTP server object
$smtp = new-object Net.Mail.SmtpClient($smtpServer)


#E-mail structure
Function EmailStructure($to,$expiryDate,$upn)
{
        $msg.IsBodyHtml = $true
        $msg.From = "notification@domain.com"
        $msg.To.Clear()
        $msg.To.Add($to)
        $msg.Subject = "Password expiration notice"
        $msg.Body =</pre><code> "<html><body><font face='Arial'>This is an automatically generated message from Exchange service.<br><br><b>Please note that the password for your account <i><u>Domain\$upn</u></i> will expire on $expiryDate.</b><br><br>Please change your password immediately or at least before this date as you will be unable to access the service without contacting your administrator.</font></body></html>"</code><pre>
}

Function EmailStructureReport($to)
{
        $msgr.IsBodyHtml = $true
        $msgr.From = "notification@domain.com"
        $msgr.To.Add($to)
        $msgr.Subject = "Script running report"
        $msgr.Body = </pre><code>"<html><body><font face='Arial'><b>This is a daily report.<br><br>Script has successfully completed its work.<br>$NotificationCounter users have recieved notifications:<br><br>$ListOfAccounts<br><br></b></font></body></html>"</code><pre>
}

#Set the target OU that will be searched for user accounts
$OU = "OU=Organisation,DC=domain,DC=local"

</pre><code>$ADAccounts = Get-ADUser -LDAPFilter "(objectClass=user)" -searchbase $OU -properties PasswordExpired, extensionAttribute15, PasswordNeverExpires, PasswordLastSet, Mail, Enabled | Where-object {$_.Enabled -eq $true -and $_.PasswordNeverExpires -eq $false}</code><pre>
$NotificationCounter = 0
$ListOfAccounts = ""

Foreach ($ADAccount in $ADAccounts)
{
 $accountFGPP = Get-ADUserResultantPasswordPolicy $ADAccount
                if ($accountFGPP -ne $null)
                {
                $maxPasswordAgeTimeSpan = $accountFGPP.MaxPasswordAge
                }
                else
                {
                $maxPasswordAgeTimeSpan</pre><code> = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge</code><pre>
                }

#Fill in the user variables
        $samAccountName = $ADAccount.samAccountName
        $userEmailAddress = $ADAccount.ExtensionAttribute15
        $userPrincipalName = $ADAccount.UserPrincipalName

        if ($ADAccount.PasswordExpired)
        {
        Write-host "The password for account $samAccountName has expired!"
        }
        else
        {
        $ExpiryDate = $ADAccount.PasswordLastSet + $maxPasswordAgeTimeSpan
        $TodaysDate = Get-Date
        $DaysToExpire = $ExpiryDate - $TodaysDate
#Calculating DaysToExpireDD to DD format (w/o fractional part and dot)
        $DaysToExpireDD = $DaysToExpire.ToString() -Split ("\S{17}$")
        Write-host </pre><code>"The password for account $samAccountName expires on: $ExpiryDate. Days left: $DaysToExpireDD"</code><pre>
                if (($DaysToExpire.Days -eq 15) -or </pre><code>($DaysToExpire.Days -eq 7) -or ($DaysToExpire.Days -le 3))</code><pre>
                {
                $expiryDate = $expiryDate.ToString("d",$ci)
#Generate e-mail structure and send message
                        if ($userEmailAddress)
                        {
                          EmailStructure $userEmailAddress $expiryDate $samAccountName
                          $smtp.Send($msg)
                            Write-Host </pre><code>"NOTIFICATION - $samAccountName :: e-mail was sent to $userEmailAddress"</code><pre>
                            $NotificationCounter = $NotificationCounter + 1
                            $ListOfAccounts = </pre><code>$ListOfAccounts + $samAccountName + " - $DaysToExpireDD days  left. Sent to $userEmailAddress<br>"</code><pre>
                        }
                  }
        }
}
Write-Host "SENDING REPORT TO IT DEPARTMENT"
EmailStructureReport("itdepartment@domain.com")
$smtp.Send($msgr)

взято с https://habrahabr.ru/post/160599/

Имеется сервер EXCHANGE 2016
Про скрипт: Анонимная отправка от любого ящика работает,
а вот отправка от существующего ящика нет.
Подскажите пожалуйста, что необходимо добавить в код для аутентификации и авторизации, дабы отправка происходила от реального ящика.
или быть может имеет смысл запускать скрипт на самом EXchange ?
Всем спасибо!

Kazun 21-03-2018 08:38 2804581

Код:

Send-MailMessage ....... -Credential "" -Port 587 -UseSsl
или

Код:

$SMTP = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTP.EnableSsl = $true
$SMTP.Credentials = New-Object System.Net.NetworkCredential("username", "password")
$SMTP.Send($SMTPMessage)


android63rus 19-11-2018 14:45 2841469

Доброго времени суток, вопрос следующий:
так как у пользователей не всегда есть электронная почта, можно ли допилить скрипт, для отправки уведомления в почту руководителя пользователя?
дабы все равно оповестить, хотя бы руководителя, имеющего корп.почту.
спасибо.

Kazun 19-11-2018 15:26 2841480

Добавить свойство manager:
Код:

Get-ADUser -LDAPFilter "(objectClass=user)" -searchbase $OU -properties manager, ....
Добавить код:

Код:

$managerEmailAddress = (Get-ADUser $ADAccount.manager -Properties mail).mail
if (-not $userEmailAddress -and $managerEmailAddress)
{
                          EmailStructure $managerEmailAddress  $expiryDate $samAccountName
                          $smtp.Send($msg)
                            Write-Host </pre><code>"NOTIFICATION - $samAccountName :: e-mail was sent to $managerEmailAddress"</code><pre>
                            $NotificationCounter = $NotificationCounter + 1
                            $ListOfAccounts = </pre><code>$ListOfAccounts + $samAccountName + " - $DaysToExpireDD days  left. Sent to $managerEmailAddress<br>"</code><pre>
}


android63rus 21-11-2018 14:47 2841895

Cпасибо, а если у некоторых пользователей есть почта, а других нет, как тогда быть?
Отправляться почта будет принудительно менеджеру? или как-то можно сделать так, чтобы если есть почта- то юзеру, а если нету- тогда уже менеджеру.
подскажите пожалуйста

android63rus 23-11-2018 09:04 2842231

HTML код:

$managerEmailAddress = (Get-ADUser $ADAccount.manager -Properties mail).mail
if (-not $userEmailAddress -and $managerEmailAddress)
{
 EmailStructure $managerEmailAddress $expiryDate $samAccountName
 $smtp.Send($msg)
 Write-Host </pre><code>"NOTIFICATION - $samAccountName :: e-mail was sent to $managerEmailAddress"</code><pre>
 $NotificationCounter = $NotificationCounter + 1
 $ListOfAccounts = </pre><code>$ListOfAccounts + $samAccountName + " - $DaysToExpireDD days left. Sent to $managerEmailAddress<br>"</code><pre>
} [post=2841895]»[/post]

при вставке этого куска кода вот что:
Get-ADUser : Не удается проверить аргумент для параметра "Identity". Аргумент имеет значение NULL. Укажите допустимое значение аргумента, после чего повторите выполнение команды.

+ $managerEmailAddress = (Get-ADUser $ADAccount.manager -Properties mai ...
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADUser


Время: 14:21.

Время: 14:21.
© OSzone.net 2001-