Link to home
Start Free TrialLog in
Avatar of Zacharia Kurian
Zacharia KurianFlag for Kuwait

asked on

Requires a power shell script to send email with login user name & IP, on Remote Desktop Connection in Windows 2012 R2 Server

I would like to create email notification for remote desktop connection to windows 2012 R2 server. Since email notification is deprecated in windows 2012, I would like to do the same with a script. The script should be able to send email notification with the login user name and the destination IP .

If the script gurus can provide me a detailed one, that would be of great help.

Zac.
Avatar of Tahir Qureshi
Tahir Qureshi
Flag of Australia image

do you want to know who is currently login to windows 2012 R2 server?

or as soon as someone login to windows 2012 r2 server it will send an email notification?
Avatar of Zacharia Kurian

ASKER

I just need an email alert when some one login to windows 2012 R2 server but with the login name and the destination IP.

Thank you.
Add-PSSnapin Microsoft.Exchange.Management.Powershell.Admin -erroraction silentlyContinue
$smtpServer = "127.0.0.1"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)

$msg.From = "emailadmin@test.com"
$msg.To.Add("administrator1@test.com")
$msg.To.Add("administrator2@test.com")
$msg.To.Add("administrator3@test.com")

$msg.Subject = "Email Test"

$IPAddresses = Get-NetIPAddress -AddressFamily IPv4 | where { $_.InterfaceAlias -notmatch 'Loopback'} |Select IPAddress;
$UserName = $env:UserName;

$msg.Body = $UserName $IPAddresses
$smtp.Send($msg)
$att.Dispose()

Open in new window

import-module ActiveDirectory
$domain = $env:USERDOMAIN
cls
write-host("The domain is " + $domain)
$samaccountname = $env:USERNAME
$userupn = Get-ADUser -Identity $samaccountname | select -expandproperty UserPrincipalName
$myForest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
$domaincontrollers = $myforest.Sites | % { $_.Servers } | Select Name
$RealUserLastLogon = $null
$LastusedDC = $null
foreach ($DomainController in $DomainControllers) 
{
	
		$UserLastlogon = Get-ADUser -Identity $samaccountname -Properties LastLogon -Server $DomainController.Name
$UserLastlogon | fl
	if ($RealUserLastLogon -le [DateTime]::FromFileTime($UserLastlogon.LastLogon))
		{
			$RealUserLastLogon = [DateTime]::FromFileTime($UserLastlogon.LastLogon)
			$LastusedDC =  $DomainController.Name
		}
}

write-host($samaccountname  + ' last logged in ' + $RealUserLastLogon + ' on Computer: ' + $env:computername)
Write-Host("Searching Security event log on {0}" -f $env:computername)
$maxdate = $RealUserLastLogon.AddSeconds(1)
$mindate = $RealUserLastLogon.AddSeconds(-1)
$events = Get-EventLog -LogName Security -After $mindate -Before $maxdate  -ComputerName $env:computername|
Where-Object -FilterScript {
  (4624, 4778) -contains $_.EventID
} |
ForEach-Object -Process {
  (New-Object -TypeName PSObject -Property @{
      TimeGenerated = $_.TimeGenerated
      ClientIP      = $_.Message -replace '(?smi).*Source Network Address:\s+([^\s]+)\s+.*', '$1'
      UserName      = $_.Message -replace '(?smi).*Account Name:\s+([^\s]+)\s+.*', '$1'
      UserDomain    = $_.Message -replace '(?smi).*Account Domain:\s+([^\s]+)\s+.*', '$1'
      LogonType     = $_.Message -replace '(?smi).*Logon Type:\s+([^\s]+)\s+.*', '$1'
  })
} |
Sort-Object -Property TimeGenerated -Descending |
Select-Object -Property TimeGenerated, ClientIP `
, @{
  N = 'Username'
  E = {
    '{0}\{1}' -f $_.UserDomain, $_.UserName
  }
} `
, @{
  N = 'LogType'
  E = {
    switch ($_.LogonType) {
      2   
      {
        'Interactive (logon at keyboard and screen of system)'
      }
      3   
      {
        'Network (i.e. connection to shared folder)'
      }
      4   
      {
        'Batch (i.e. scheduled task)'
      }
      5   
      {
        'Service (i.e. service start)'
      }
      7   
      {
        'Unlock (i.e. post screensaver)'
      }
      8   
      {
        'NetworkCleartext (i.e. IIS)'
      }
      9   
      {
        'NewCredentials (i.e. local impersonation process under existing connection)'
      }
      10  
      {
        'RemoteDesktop'
      }
      11  
      {
        'CachedInteractive (i.e. interactive, but without network connection to validate against AD)'
      }   
      default 
      {
        "LogType Not Recognised: $($_.LogonType)"
      }     
    }
  }
} 
$user = $env:USERDOMAIN + "\" + $samaccountname
write-host ("Checking logon Events")
foreach($event in $events){

#$event
if (($event.Username -eq $user) -and ($event.LogType -eq 'RemoteDesktop')) 
    {  
    $body =  $event.Username + " RDP login from Remote IP: " + $event.ClientIP 
<#  
    $to = admin@domain.com
    $from = $userupn
    $subject = "User Logged in from Remote Desktop"
    
    Send-MailMessage -to $to -from -from -subject -subject -body $body
#>    
    
     break
      }
}

Open in new window

I just need a very simple script to send an email alert when some one login into a windows 2012 server, but with details such as;

1. logged in user
2. destination IP

Once I have a scrip to do so, I can attach a scheduled task to the login event id 4624.

Thank you
The email alert for such would be as below;
User generated image
Just to confirm, you've continually referred to the IP address used as a destination IP. Do you want to capture the IP address of the server?

Excluding IP for a moment, perhaps the simplest way to trigger the script is to add it to All users \ Startup, but you might also push it into the registry (Run).

You should not need anything much more complex than this:
$messageBody = 'Login Alert on {0}.{1} User: {3}' -f
    $env:COMPUTERNAME,
    $env:USERDNSDOMAIN,
    $env:USERNAME
Send-MailMessage -To IT@domain.com -From blank@domain.com -Subject "RDP Login Details" -Body $messageBody -SmtpServer someserver

Open in new window

Chirs,

Thanks for the reply. I was referring to the site http://pingforinfo.com/receive-e-mail-alert-on-rdp-login-at-windows-servers/
which comes very close to my requirement. But then, it doesn't work as expected.

Zac.
No IP address and it's running for the last logged on user based on quser... I felt you were looking for something simpler which is why I picked on environment variables.

There's a few difficulties though, initially based on inherent limitations. For example, if the script above is used as a start-up script (by whatever means), it won't run if someone re-connects to a disconnected session. Would the original alerting feature have done so?
Tahir,

Ok. I just got a script that I tested. It gives me the login name, the session time etc.. but not the IP from where the user connected to the server. I am attaching the script.

If the parameters to get the IP can be added  to this script, then I could test it. I am not well versed with scripts at all.


Zac.
getrdp.txt
to get the Local IP address you can use the following command and add this to your script

$LocalIP = Get-NetTCPConnection -State Established -RemotePort 3389 | Select LocalAddress

<#
 Add the $LocalIP variable to your body section of your script  
Here I am using Port Number 3389 which is use for remote access you can change this If you have configure it differently 
State i have configure as Established (you can change to something whatever you like )

#>

Open in new window

That did not work. The one I attached  in the previous post, is giving me the details;

User Name      Computer Name      State      Logon Time      Session Name.

I need to have another column named "Remote IP" and then a command to fetch  the Remote IP to this column.

Zac.
did you even try the code sample that I submitted? the event log query is slow but it does return the correct results
ASKER CERTIFIED SOLUTION
Avatar of Tahir Qureshi
Tahir Qureshi
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
you want the ip of the computer the user is on and started remote desktop connection right? or do you want the machine that they logged into?
David,

Yes I want "the ip of the computer the user is on and started remote desktop connection".

Zac.
Perhaps you can use the ClientName environmental variable
Then you need to use the slow script that queries the security log