2

PowerShell监测AD账号锁定并发送到钉钉消息

 5 months ago
source link: https://blog.51cto.com/magic3/10245035
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

PowerShell监测AD账号锁定并发送到钉钉消息

精选 原创

史振宁的技术博客 2024-03-28 16:07:30 博主文章分类:ActiveDirectory ©著作权

文章标签 AD账号锁定 文章分类 运维 yyds干货盘点 阅读数138

尝试过将监测脚本作为服务运行的方式,也尝试了通过 监测EventLog 4740的方式(遍历所有DC导致脚本效率低),详见  监测4740EventLog

两种方式都不能满意。于是,继续在原始脚本上进行优化。

脚本优化的目标两个: 1. 定时任务间隔可以尽量缩小。 2.用户账号锁定后,只收取一次消息通知。

Import-Module activedirectory

$Users = Search-ADAccount -searchbase "OU=Emp,OU=Im,DC=im,DC=com" -LockedOut | Select-Object -ExpandProperty SamAccountName

ForEach ($User in $Users){
    $Users_Info = Get-AdUser $User -Properties displayname,mail,AccountLockoutTime
    $CN = $Users_Info.cn
    $User_DisplayName = $Users_Info.DisplayName
    $UserMail=$Users_Info.mail

    $bodymessage="你好,"+$User_DisplayName+":<br>
   您的邮箱账户已经锁定。<br>
   请立即用电脑或者手机浏览器,打开网页邮箱,用【解锁账户】按钮自主解锁账户。<br>
"
    
    $postParams = @{ emails=$UserMail;appSecret='xAYsx';appKey='uvvf';text=$bodymessage;title='账号锁定提醒!';source='IT支持'}| ConvertTo-Json

    $To_CN = [System.Text.Encoding]::UTF8.GetBytes($postParams)
    Invoke-WebRequest -Uri http://xxxxx -Method POST -ContentType "application/json" -Body $To_CN
    
}

优化后脚本:

Import-Module activedirectory

$starttime=(Get-Date).AddMinutes(-2)
$Users = Search-ADAccount -searchbase "OU=Emp,OU=Im,DC=im,DC=com" -LockedOut | Select-Object -ExpandProperty SamAccountName

ForEach ($User in $Users){
    $Users_Info = Get-AdUser $User -Properties displayname,mail,AccountLockoutTime
    $CN = $Users_Info.cn
    $User_DisplayName = $Users_Info.DisplayName
    $UserMail=$Users_Info.mail
    $locktime=$Users_Info.AccountLockoutTime

    $bodymessage="你好,"+$User_DisplayName+":<br>
   您的邮箱账户已经锁定。<br>
   锁定时间:$locktime。 <br>
   请立即用电脑或者手机浏览器,打开网页邮箱,用【解锁账户】按钮自主解锁账户。<br>
"
    
    $postParams = @{ emails=$UserMail;appSecret='xAYsx';appKey='uvvf';text=$bodymessage;title='账号锁定提醒!';source='IT支持'}| ConvertTo-Json
    #$postParams
    $To_CN = [System.Text.Encoding]::UTF8.GetBytes($postParams)
    if($locktime -ge $starttime){
        Invoke-WebRequest -Uri http://xxxxx -Method POST -ContentType "application/json" -Body $To_CN
    }
}
  
  • 说明
    • $starttime 一个供参考的时间字段,脚本启动前的某个时间点,可以理解为定时任务间隔。

    • $locktime 账号锁定时间字段

定时任务间隔设置为$starttime 变量中AddMinutes(-2)的参数,即2分钟。

发送消息之前,增加一个判断 if($locktime -ge $starttime) 如果锁定时间大于等于参考时间点,即锁定动作发生在上次定时任务完成后,才给用户发送消息。 这样就杜绝了,重复给用户发送锁定消息。

  • 收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK