Powershell监控操做系统用户帐号事件并预警

#  
# 操做系统帐号事件(登陆、注销、新增、删除、软件安装)  
# 主函数 Main  
# @param string $str not null  
# @param string $code not null  
#   
# Description:  
# 设置登陆事件的任务计划时,必须传递这两个参数  
#  
  
#region get-serverip 获取IP  
function get-serverip  
{  
    $serverip=gwmi win32_networkadapterconfiguration | ?{$_.IPAddress -ne $null -and $_.dhcpenabled -eq $false -and {$_.IPEnabled}} | %{$_.IPAddress}  
    if(($serverip.gettype()).isarray)  
    {  
        return $serverip[0]  
    }  
    else  
    {  
        return $serverip  
    }  
}  
#endregion  
  
#region Send-Mail 发送邮件  
function Send-Mail($Subject,$Body)  
{  
    $password = ConvertTo-SecureString 'password' -AsPlainText -Force  
    $Credential = New-Object System.Management.Automation.PSCredential('account',$password)  
    $SmptServer="<a target="_blank" href="http://bxing.net">mail.xx.com.cn</a>"  
    <a target="_blank" href="mailto:$From='a@xx.com.cn'">$From='a@xx.com.cn'  
</a>    $To="test@xx.com.cn"  
      
    #抄送  
    #$Cc="cc@xx.com.cn"  
    $encode=[System.Text.UTF8Encoding]::UTF8  
  
    Send-MailMessage -SmtpServer $SmptServer -Credential $Credential -From $From -to $To -Encoding $Encode -Body $Body -Subject $Subject -Priority High -BodyAsHtml  
}  
#endregion  
  
#region cut-string 裁剪字符串  
function cut-string   
{  
    param(  
        $str,  
        $start,  
        $end  
    )  
    return $str.substring($str.indexof($start),$str.indexof($end)-$str.indexof($start))  
}  
#endregion  
  
#region get_login_user 获取登陆帐户  
#return string  
function get_login_user  
{  
    $users=query user  
  
    $lists=New-Object system.Collections.ArrayList  
  
    for($i=1;$i -lt $users.Count;$i++)  
    {  
        $user = $users[$i] -replace('  ',' ')  
          
        while($user.indexof('  ') -gt 0)  
        {  
            $user = $user -replace('  ',' ')  
        }  
        if($user.indexof(' ') -eq 0 -or $user.indexof('>') -eq 0)  
        {  
            $user=$user.substring(1)  
        }  
        $user=$user -split(' ')  
          
        $list=New-Object psobject  
        #$time=$user[5]+" "+$user[6]  
  
        Add-Member -Name name -Value $user[0] -MemberType NoteProperty -InputObject $list  
        Add-Member -Name status -Value $user[3] -MemberType NoteProperty -InputObject $list  
        #Add-Member -Name time -Value $time -MemberType NoteProperty -InputObject $list  
        $lists +=@($list)  
    }  
  
    $loginUser = $lists | ?{$_.status -eq '运行中'} | select name  
    foreach($userName in $loginUser)  
    {     
        if($userNames -eq $null)  
        {  
            $userNames=$userName.name  
        }  
        else  
        {  
            $userNames=$userNames + ',' + $userName.name  
        }  
    }  
    return $userNames  
}  
#endregion  
  
#region Login-Succ-Notice 成功登陆事件  
function Login-Succ-Notice  
{  
    $loginInfo=Get-WinEvent -logname security -maxevents 10 | ? {$_.id -eq 4624} | select timecreated,message  
    if($loginInfo -eq $null)  
    {  
        break  
    }  
    if(($loginInfo.gettype()).isarray)  
    {  
        $time=$loginInfo[0].timecreated  
        $message=$loginInfo[0].message  
    }  
    else  
    {  
        $time=$loginInfo.timecreated  
        $message=$loginInfo.message  
    }  
      
    if($code -eq 1)  
    {  
        $loginType=cut-string $message '登陆类型:' '新登陆:'  
        $loginType=$loginType -replace('登陆类型:','')  
        $loginType=$loginType -replace('            ','')  
        if($loginType -eq 4)  
        {  
            break  
        }  
    }  
      
    $processInfo=cut-string $message '进程名:' '网络信息:'  
    $processInfo=$processInfo -replace('进程名:        ','')  
      
    $message=cut-string $message '新登陆' '详细身份验证信息'  
    $loginName=cut-string $message '账户名:' '账户域:'  
    $loginName=$loginName -replace('账户名:','')  
      
    $loginIp=cut-string $message '源网络地址:' '源端口:'  
    $loginIp=$loginIp -replace('源网络地址:','')  
      
    $ip=get-serverip  
    $loginedName=get_login_user  
    $Body="<table width='700' border='1' cellpadding='0' cellspacing='0' style='font-size:13px;'>  
  <tr  style='background:#39F'>  
    <td>服务器</td>  
    <td>登陆帐号</td>  
    <td>进程</td>  
    <td>登陆时间</td>  
    <td>客户端IP</td>  
    <td>已登陆帐号</td>  
  </tr>  
  <tr>  
    <td>$ip</td>  
    <td>$loginName</td>  
    <td>$processInfo</td>  
    <td>$time</td>  
    <td>$loginIp</td>  
    <td>$loginedName</td>  
  </tr>  
</table>"  
    try  
    {  
        Send-Mail "Login on $ip" $Body  
    }  
    catch  
    {  
        ac -Path c:\UserNotice.log -Value "[ $time Login] $error[0]"  
    }  
}  
#endregion  
  
#region Cancel-Succ-Notice 注销登陆事件  
function Cancel-Succ-Notice  
{  
    $cancelInfo=Get-WinEvent -logname security -maxevents 10 | ? {$_.id -eq 4634} | select timecreated,message  
    if($cancelInfo -eq $null)  
    {  
        break  
    }  
    if(($cancelInfo.gettype()).isarray)  
    {  
        $time=$cancelInfo[0].timecreated  
        $message=$cancelInfo[0].message  
    }  
    else  
    {  
        $time=$cancelInfo.timecreated  
        $message=$cancelInfo.message  
    }  
    $cancelName=cut-string $message '账户名:' '账户域:'  
    $cancelName=$cancelName -replace('账户名:','')  
      
    $ip=get-serverip  
    $loginedName=get_login_user  
    $Body="<table width='700' border='1' cellpadding='0' cellspacing='0' style='font-size:13px;'>  
  <tr  style='background:#39F'>  
    <td>服务器</td>  
    <td>注销帐号</td>  
    <td>注销时间</td>  
    <td>未注销帐号</td>  
  </tr>  
  <tr>  
    <td>$ip</td>  
    <td>$cancelName</td>  
    <td>$time</td>  
    <td>$loginedName</td>  
  </tr>  
</table>"  
    try  
    {  
        Send-Mail "Cancel on $ip" $Body  
    }  
    catch  
    {  
        ac -Path c:\UserNotice.log -Value "[ $time Cancel] $error[0]"  
    }  
}  
#endregion  
  
#region Create-User-Notice 新增帐号事件  
function Create-User-Notice  
{  
    $userinfo=Get-WinEvent -logname security -maxevents 10 | ? {$_.id -eq 4722} | select timecreated,message  
    if($userinfo -eq $null)  
    {  
        break  
    }  
    if(($userinfo.gettype()).isarray)  
    {  
        $time=$userinfo[0].timecreated  
        $message=$userinfo[0].message  
    }  
    else  
    {  
        $time=$userinfo.timecreated  
        $message=$userinfo.message  
    }  
    $operateUser=cut-string $message '主题:' '目标账户:'  
    $operateUser=cut-string $operateUser '账户名:' '账户域:'  
    $operateUser=$operateUser -replace('账户名:','')  
      
    $addUser=$message.substring($message.indexof('目标账户:'))  
    $addUser=cut-string $addUser '账户名:' '账户域:'  
    $addUser=$addUser -replace('账户名:','')  
      
    $ip=get-serverip  
    $loginedUser=get_login_user  
      
    $Body="<table width='700' border='1' cellpadding='0' cellspacing='0' style='font-size:13px;'>  
  <tr  style='background:#39F'>  
    <td>服务器</td>  
    <td>操做帐号</td>  
    <td>被添加帐号</td>  
    <td>操做时间</td>  
    <td>已登陆帐号</td>  
  </tr>  
  <tr>  
    <td>$ip</td>  
    <td>$operateUser</td>  
    <td>$addUser</td>  
    <td>$time</td>  
    <td>$loginedUser</td>  
  </tr>  
</table>"  
    try  
    {  
        Send-Mail "AddUser on $ip" $Body  
    }  
    catch  
    {  
        ac -Path c:\UserNotice.log -Value "[ $time AddUser] $error[0]"  
    }  
}  
#endregion  
  
#region Delete-User-Notice 删除帐号事件  
function Delete-User-Notice{  
  
    $userInfo=Get-WinEvent -logname security -maxevents 10 | ? {$_.id -eq 4726} | select timecreated,message  
    if($userinfo -eq $null)  
    {  
        break  
    }  
    if(($userinfo.gettype()).isarray)  
    {  
        $time=$userinfo[0].timecreated  
        $message=$userinfo[0].message  
    }  
    else  
    {  
        $time=$userinfo.timecreated  
        $message=$userinfo.message  
    }  
    $ip=get-serverip  
    $loginedUser=get_login_user  
      
    $operateUser=cut-string $message '主题:' '目标账户:'  
    $operateUser=cut-string $operateUser '账户名:' '账户域:'  
    $operateUser=$operateUser -replace('账户名:','')  
    $delUser=$message.substring($message.indexof('目标账户:'))  
    $delUser=cut-string $delUser '账户名:' '账户域:'  
    $delUser=$delUser -replace('账户名:','')  
      
    $Body="<table width='700' border='1' cellpadding='0' cellspacing='0' style='font-size:13px;'>  
  <tr  style='background:#39F'>  
    <td>服务器</td>  
    <td>操做帐号</td>  
    <td>被删除帐号</td>  
    <td>操做时间</td>  
    <td>已登陆帐号</td>  
  </tr>  
  <tr>  
    <td>$ip</td>  
    <td>$operateUser</td>  
    <td>$delUser</td>  
    <td>$time</td>  
    <td>$loginedUser</td>  
  </tr>  
</table>"  
    try  
    {  
        Send-Mail "Delete on $ip" $Body  
    }  
    catch  
    {  
        ac -Path c:\UserNotice.log -Value "[ $time Delete] $error[0]"  
    }  
}  
#endregion  
  
#region Software-Setup-Notice 软件安装事件  
function Software-Setup-Notice  
{  
    $softinfo=Get-WinEvent -logname setup -maxevents 10 | ? {$_.id -eq 1610} | select timecreated,message  
    if($softinfo -eq $null)  
    {  
        break  
    }  
    if(($softinfo.gettype()).isarray)  
    {  
        $time=$softinfo[0].timecreated  
        $time=$softinfo[0].tostring()  
        $message=$softinfo[0].message  
    }  
    else  
    {  
        $time=$softinfo.timecreated  
        $time=$time.tostring()  
        $message=$softinfo.message  
    }  
    $ip=get-serverip  
    $loginedUser=get_login_user  
      
    $Body="<table width='700' border='1' cellpadding='0' cellspacing='0' style='font-size:13px;'>  
  <tr  style='background:#39F'>  
    <td>服务器</td>  
    <td>已登陆帐号</td>  
    <td>安装时间</td>  
    <td>安装信息</td>  
  </tr>  
  <tr>  
    <td>$ip</td>  
    <td>$loginedUser</td>  
    <td>$time</td>  
    <td>$message</td>  
  </tr>  
</table>"  
  
    try  
    {  
        Send-Mail 'Setup on $ip' $Body  
    }  
    catch  
    {  
        ac -Path c:\UserNotice.log -Value "[ $time Setup] $error[0]"  
    }  
}  
#endregion  
  
#region Main 入口函数  
function Main{  
  
    param(  
    $str,  
    $script:code  
    )  
      
    if($str -eq $null)  
    {  
        Write-Warning 参数丢失!  
        sleep 2  
        break  
    }  
    if($str -eq 'login')  
    {  
        Login-Succ-Notice  
    }  
    if($str -eq 'cancel')  
    {  
        Cancel-Succ-Notice  
    }  
    if($str -eq 'add')  
    {  
        Create-User-Notice  
    }  
    if($str -eq 'delete')  
    {  
        Delete-User-Notice  
    }  
    if($str -eq 'setup')  
    {  
        Software-Setup-Notice  
    }  
}  
#endregion  
  
main $args[0] $args[1]