Thursday, December 29, 2016

Nslookup with PowerShell

I needed a method of validating that  our PTR records matched our DNS records.  I found a lot of scripts that did pieces of each.  I created a script that uses the nslookup tool in Windows and parses the results.  This version does one host at a time but I'm working on integrating it into my DNS validator script.  This is a quick and dirty script, feel free to use it as you see fit.

#Requires -version 3.0
Clear-Host

$Target = "hostname"
Write-Host "Target Hostname = $Target" -ForegroundColor Yellow

$HostLookup = (nslookup $Target )
$Lookup = [PSCustomObject]@{
    DNS_Host = ($HostLookup[0] -split ‘:’)[1].Trim()
      DNS_IP = ($HostLookup[1] -split ‘:’)[1].Trim()
 Target_Host = ($HostLookup[3] -split ‘:’)[1].Trim()
   Target_IP = ($HostLookup[4] -split ‘:’)[1].Trim()
}

Write-Host "Target IP from NSLOOKUP ="$Lookup.Target_IP -ForegroundColor Cyan

$IPLookup = (nslookup $Lookup.Target_IP )
$RevLookup = [PSCustomObject]@{
    DNS_Host = ($IPLookup[0] -split ‘:’)[1].Trim()
      DNS_IP = ($IPLookup[1] -split ‘:’)[1].Trim()
 Target_Host = ($IPLookup[3] -split ‘:’)[1].Trim()
   Target_IP = ($IPLookup[4] -split ‘:’)[1].Trim()
}

If ($Lookup.DNS_Host -ne $RevLookup.DNS_Host){Write-Host DNS Host Mismatch -ForegroundColor Red}
ElseIf($Lookup.DNS_IP -ne $RevLookup.DNS_IP){Write-Host DNS IP Mismatch -ForegroundColor Red}
ElseIf ($Lookup.Target_Host -ne $RevLookup.Target_Host){Write-Host IP Mismatch -ForegroundColor Red}
ElseIf ($Lookup.Target_IP -ne $RevLookup.Target_IP){Write-Host IP Mismatch -ForegroundColor Red}
Else {Write-Host No Mismatch Found -ForegroundColor Green}

$Lookup.PsObject.Members|%{$Lookup.PsObject.Members.Remove($_.Name)}

$RevLookup.PsObject.Members|%{$RevLookup.PsObject.Members.Remove($_.Name)}

Monday, November 14, 2016

SMTP Test Script with GUI

Here is a little script I worked up some time ago to test my SMTP relay.  It brings up a GUI where you populate the required info, saves that for the next run, and sends out a test email.

NOTE: The new version and all subsequent updates are at the PowerShell Gallery at https://www.powershellgallery.com


<#==============================================================================
         File Name : SMTP_Relay_Test.ps1
   Original Author : Kenneth C. Mazie (kcmjr AT kcmjr.com)
                   :
       Description : This script will send an email to the selected user,
                   : SMTP host, and SMTP port.
                   :
                   : The target email and server IP are stored and recalled for
                   : subsequent runs.
                   :
             Notes : Normal operation is with no command line options.
                   :
          Warnings : None
                   :
             Legal : Public Domain. Modify and redistribute freely. No rights reserved.
                   : SCRIPT PROVIDED "AS IS" WITHOUT WARRANTIES OR GUARANTEES OF 
                   : ANY KIND. USE AT YOUR OWN RISK. NO TECHNICAL SUPPORT PROVIDED.
                   :
           Credits : Code snippets and/or ideas came from many sources including but 
                   :   not limited to the following:
                   :
    Last Update by : Kenneth C. Mazie
   Version History : v1.0 - 06-26-12 - Original
$CurrentVersion = "1.0"
    Change History : v1.1 - 00-00-00 - 
                   :
===============================================================================#>

Clear-Host
[System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") | Out-null 
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null

#--[ Variables ]--
[string]$Username = "user@domain.com"     #--[ SSL authentication user. Adjust per environment
[string]$Password = "Password"            #--[ SSL password. Adjust per environment

$erroractionpreference = "continue"
if (!(Test-Path -pathtype Container "C:\Scripts")){
new-item C:\Scripts -itemType Directory -Force                                                  #--[ Create local scripts folder. 
}
if (Test-Path c:\Scripts\eMailRecipient.txt) {
      [string]$eMailRecipient = Get-Content c:\Scripts\eMailRecipient.txt           #--[ This should be stored as email@domain.com, one line, one entry only
      [string]$eMailDomain = $eMailRecipient.Split("@")[1]
      }else{[string]$eMailRecipient = "";[string]$eMailDomain = ""
if (Test-Path c:\Scripts\eMailServer.txt) {
      [string]$SMTPserver = Get-Content c:\Scripts\eMailServer.txt                        #--[ This should be stored as one line, one entry only
      }else{[string]$SMTPserver = ""}
$date = Get-Date
[int]$FormWidth = 350
[int]$FormHeight = 240
$fcenter = ($fswidth / 2)
[int]$ButtonLeft = 55
[int]$ButtonTop = 167

#--[ FQDN of the local computer ]--
$objCompSys = Get-WmiObject win32_computersystem
$localComputer = $objCompSys.name+"."+$objCompSys.domain
Remove-Variable objCompSys

#--[ Functions ]--
Function ProcessMessage {
New-Item c:\Scripts\eMailRecipient.txt -type file -Value "$eMailRecipient@$eMailDomain" -Force -Confirm:$false        #--[ Who to send status email to. 
New-Item c:\Scripts\eMailServer.txt -type file -Value "$SMTPserver" -Force -Confirm:$false          #--[ What server to send through. 

$MailMessage = New-Object System.Net.Mail.MailMessage
$MailMessage.IsBodyHtml = $true
$SMTPserverClient = New-Object System.Net.Mail.smtpClient
$SMTPserverClient.host = $SMTPserver
If ($P465RadioButton.checked){
      $SMTPport = 465
      $SMTPserverClient.EnableSsl = $true
      $SMTPserverClient.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
      }
If ($P25RadioButton.checked){
      $SMTPport = 25
      $SMTPserverClient.EnableSsl = $false
      $SMTPserverClient.Credentials = $null
      }
     
#--[ Build Message Body ]--
$strBody = @"
<html><body>
<p>This is a SMTP test email.  Below are the details specific to this test email:
<p>
<table border='1'>
      <TR>
            <th WIDTH='50%'>Originating Computer</th>
            <th WIDTH='50%'>$localComputer</th>
      </TR>
      <TR>
            <th WIDTH='50%'>SMTP Server Address</th>
            <th WIDTH='50%'>$SMTPserver</th>
      </TR>
      <TR>
            <th WIDTH='50%'>SMTP Server Port</th>
            <th WIDTH='50%'>$SMTPport</th>
      </TR>
      <TR>
            <th WIDTH='50%'>Return Address (Sender)</th>
            <th WIDTH='50%'>SMTPtest@$eMailDomain</th>
      </TR>
      <TR>
            <th WIDTH='50%'>Recipient</th>
            <th WIDTH='50%'>$eMailRecipient@$eMailDomain</th>
      </TR>
            <TR>
            <th WIDTH='50%'>Date / Time</th>
            <th WIDTH='50%'>$date</th>
      </TR>
</table>
<p> The SMTP test has <b>COMPLETED SUCCESSFULLY</b> if you receive this email!
</body></html>
"@

$Recipient = New-Object System.Net.Mail.MailAddress("$eMailRecipient@$eMailDomain")
$Sender = New-Object System.Net.Mail.MailAddress("SMTPtest@$eMailDomain")
$SMTPserverClient.port = $SMTPport
$MailMessage.Subject = "Test SMTP email over port $SMTPport from $SMTPserver"
$MailMessage.Sender = $Sender
$MailMessage.From = $Sender
$MailMessage.To.add($Recipient)
$MailMessage.Body = $strBody

Try {$SMTPserverClient.Send($MailMessage)}
Catch {
      [System.Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”)
      [Windows.Forms.MessageBox]::Show($Error[0], “Error Sending Email”, [Windows.Forms.MessageBoxButtons]::OK, [Windows.Forms.MessageBoxIcon]::Information)
      }
$objForm.Close()
}


#-----------------------------[ Main Process ]----------------------------------
#--[ Create Form ]--
$objForm = new-object System.Windows.Forms.form
$objForm.Text = "SMTP Test Script"
$objForm.size = new-object System.Drawing.Size($FormWidth,$FormHeight)
$objForm.StartPosition = "CenterScreen"

$objForm.KeyPreview = $true
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter"){$Recipient=$objTextBox.Text;$objForm.Close()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape"){$objForm.Close();$Stop = $true}})

#--[ Add Form Lable ]--
$objFormLabelBox = new-object System.Windows.Forms.Label
$objFormLabelBox.Font = new-object System.Drawing.Font("New Times Roman",9,[System.Drawing.FontStyle]::Bold)
$objFormLabelBox.Location = new-object System.Drawing.Size(38,5)
$objFormLabelBox.size = new-object System.Drawing.Size(400,20)
$objFormLabelBox.Text = "Select SMTP test parameters to use:"
$objForm.Controls.Add($objFormLabelBox)

#--[ Add port 25 Radio Button ]--
$P25RadioButton = New-Object Windows.Forms.radiobutton
$P25RadioButton.text = "Use Port 25  (anonymous connection)"
$P25RadioButton.height = 20
$P25RadioButton.width = 220
$P25RadioButton.top = 113
$P25RadioButton.left = 65
$P25RadioButton.checked = $true
$objForm.controls.add($P25RadioButton)

#--[ Add SSL Radio Button ]--
$P465RadioButton = New-Object Windows.Forms.radiobutton
$P465RadioButton.text = "Use Port 465  (SSL connection)"
$P465RadioButton.height = 20
$P465RadioButton.width = 220
$P465RadioButton.top = 135
$P465RadioButton.left = 65
#$P465RadioButton.checked = $true
$objForm.controls.add($P465RadioButton)

#--[ Add Email Form Lable ]--
$objLabel1 = New-Object System.Windows.Forms.Label
$objLabel1.Location = New-Object System.Drawing.Point(20,25)
$objLabel1.Size = New-Object System.Drawing.Size(280,20)
$objLabel1.Text = "Enter the email address where results should be sent:"
$objLabel1.TextAlign = [System.Drawing.ContentAlignment]::MiddleCenter
$objForm.Controls.Add($objLabel1)

#--[ Add Email Text Input Box ]--
$objTextBox1 = New-Object System.Windows.Forms.TextBox
$objTextBox1.Location = New-Object System.Drawing.Size(54,48)
$objTextBox1.Size = New-Object System.Drawing.Size(100,20)
#if (Test-Path c:\Scripts\eMailRecipient.txt) {
 $objTextBox1.Text = $eMailRecipient.split("@")[0]
#}
$objForm.Controls.Add($objTextBox1)

#--[ Add Email Domain Input Box ]--
$objLabel2 = New-Object System.Windows.Forms.Label
$objLabel2.Location = New-Object System.Drawing.Point(153,50)
$objLabel2.Size = New-Object System.Drawing.Size(14,20)
$objLabel2.Text = "@"
$objForm.Controls.Add($objLabel2)

#--[ Add Email @ Label ]--
$objTextBox2 = New-Object System.Windows.Forms.TextBox
$objTextBox2.Location = New-Object System.Drawing.Point(170,48)
$objTextBox2.Size = New-Object System.Drawing.Size(100,20)
$objTextBox2.Text = $eMailDomain
$objForm.Controls.Add($objTextBox2)
#$eMailDomain = $objTextBox2.Text

#--[ Add SMTP Host Form Lable ]--
$objLabel3 = New-Object System.Windows.Forms.Label
$objLabel3.Location = New-Object System.Drawing.Point(25,70)
$objLabel3.Size = New-Object System.Drawing.Size(280,20)
$objLabel3.Text = "Enter the SMTP server to use:"
$objLabel3.TextAlign = [System.Drawing.ContentAlignment]::MiddleCenter
$objForm.Controls.Add($objLabel3)

#--[ Add SMTP Host Input Box ]--
$objTextBox3 = New-Object System.Windows.Forms.TextBox
$objTextBox3.Location = New-Object System.Drawing.Size(115,93)
$objTextBox3.Size = New-Object System.Drawing.Size(100,20)
#if (Test-Path c:\Scripts\eMailServer.txt) {
 $objTextBox3.Text = $SMTPserver
#}
$objForm.Controls.Add($objTextBox3)
#$SMTPserver = $objTextBox3.Text

#--[ Add GO Button ]--
$objProcessButton = new-object System.Windows.Forms.Button
$objProcessButton.Location = new-object System.Drawing.Size($ButtonLeft,$ButtonTop)
$objProcessButton.Size = new-object System.Drawing.Size(100,25)
$objProcessButton.Text = "Send Email"
$objProcessButton.Add_Click({$to=$objTextBox1.Text;$SMTPserver=$objTextBox3.Text;$eMailRecipient=$objTextBox1.Text;$eMailDomain=$objTextBox2.Text;ProcessMessage;$objForm.Close()})
$objForm.Controls.Add($objProcessButton)

#--[ Add STOP Button ]--
$objCloseButton = new-object System.Windows.Forms.Button
$objCloseButton.Location = new-object System.Drawing.Size(($ButtonLeft+125),$ButtonTop)
$objCloseButton.Size = new-object System.Drawing.Size(100,25)
$objCloseButton.Text = "Cancel/Close"
$objCloseButton.Add_Click({$objForm.close()})
$objForm.Controls.Add($objCloseButton)

#--[ Open Form ]--
$objForm.topmost = $true
$objForm.Add_Shown({$objForm.Activate()})
$objForm.ShowDialog()