Search LDAP Entries using Powershell

Below little script shows how to connect to Active Directory / LDAP and search for entries.

Docs: https://technet.microsoft.com/en-us/library/ff730967.aspx

$mySearcher = New-Object System.DirectoryServices.DirectorySearcher

# it is possible to specify manually a ldap search Path:
#$mySearcher.SearchRoot = "LDAP://DC=de,DC=myComapny,DC=com"

# or to get current ldap path (for example: DC=de,DC=myComapny,DC=com)
$objDomain = New-Object System.DirectoryServices.DirectoryEntry

$mySearcher.SearchRoot = $objDomain

# search for object class "user" with attribte "name=TestUser1"
$mySearcher.Filter = "(& (objectClass=user) (name=TestUser1))"
$mySearcher.SearchScope = "sub"
$mySearcher.PageSize = 10

# specifiy the attributes you would like to retrieve
$myAttributes = ("telephonenumber", "mail", "department")
# comment below line to get all attributes
$mySearcher.PropertiesToLoad.AddRange($myAttributes)

$abc = $mySearcher.FindAll()

# show all attributes and values
foreach ($i in $abc.Properties.PropertyNames){
    Write-Host $i , "=" , $abc.Properties.$i
}

The Script will generate the following output:

mail = Testuser1@mycompany.com
telephonenumber = +49XXXXXXXX
department = MyDepartment
adspath = LDAP://<removed_by_author>

OpenDS Ldap Server: Port configuration

List all conntection handlers (see also here:  http://docs.oracle.com/cd/E19476-01/821-0506/to-display-connection-handlers.html) :

 % dsconfig -h localhost -p 11998 -D "cn=Manager" -w <password> -n list-connection-handlers --trustAll
Connection Handler       : Type : enabled : listen-port : use-ssl
-------------------------:------:---------:-------------:--------
HTTP Connection Handler  : http : false   : 8080        : false
JMX Connection Handler   : jmx  : true    : 11997       : false
LDAP Connection Handler  : ldap : true    : 11999       : false
LDAPS Connection Handler : ldap : false   : 636         : true
LDIF Connection Handler  : ldif : false   : -           : -

 

Change Listen Ports (see also here: http://docs.oracle.com/cd/E19476-01/821-0506/configuring-the-ldap-connection-handler.html) :

# JMX Port
dsconfig -h localhost -p 11998 -D "cn=Manager" -w <password> -n set-connection-handler-prop \
        --handler-name "JMX Connection Handler" --set listen-port:17497  --trustAll
# LDAP Port
dsconfig -h localhost -p 11998 -D "cn=Manager" -w <password> -n set-connection-handler-prop \
          --handler-name "LDAP Connection Handler" --set listen-port:17499  --trustAll
# Admin Port
dsconfig -h localhost -p 11998 -D "cn=Manager" -w <password> -n set-administration-connector-prop \
     --set listen-port:17498  --trustAll

 

ant scp task

Ant SCP Task:

<?xml version="1.0" encoding="UTF-8"?>

<project name="MyProject" default="copyToUnix" basedir=".">

	<target name="copyToUnix">
		<scp todir="user@vserver:/var/www/myFolder/" keyfile="/Users/dummy/.ssh/id_rsa">
			<fileset dir="WebContent">
				<include name="*.php" />
			</fileset>
		</scp>
	</target>
	
</project>

You need an additional jar file for ant scp task: http://www.jcraft.com/jsch/index.html

Check certificate validation date with powershell

Little powershell script that checks the expiration date of a ssl certficate that is not added in local certificate store. We are using this script in an scheduled task to get an Warning-mail 30 days before the certficate expires.

 

# Checks the validation of a certificate 
# if the certificate expires in the next *DaysToExpiration*, an email is sent 
# to System Operations Team to inform them that they should order a new Certificate
# author: philipp.boss
# Version: 0.1  (2016-01-25)

$DaysToExpiration = 30  #notify 30 days before certificate is expired
$certFile = "D:\SSL_certs_for_filezilla\server.crt" 
# Receivers of the information message (Operations Team)
$to = @("email1@mail.com",  "email2@mail.com")
$smtpHost = "my-smtp-host.com"
$from = "userX@mail.com"  # this is the senders email address 


# check if file exists, otherwise send an email to Operations team to inform them that
# the configuration is wrong
If (Test-Path $certFile){
    $expirationDate = (Get-Date).AddDays($DaysToExpiration)

    # The certutil tool displays all information of a certificate
    # with select-string we filter for the end date of validation
    $dumpOutput = certutil.exe -dump $certFile | Select-String -Pattern ("NotAfter")
    $certificateEndDate = [datetime]::Parse( $dumpOutput.toString().Substring(11) )
    "Certificate is valid to:" 
    $certificateEndDate.ToString("dd.MM.yyyy")
    $expiresIn = $certificateEndDate.Subtract((Get-Date)).Days
    $expiresIn


    # check if certificate will expire in the next days (see variable DaysToExpiration)
    if ($certificateEndDate  -lt $expirationDate) {
        $expiresIn = $expiresIn = $certificateEndDate.Subtract((Get-Date)).Days
        $subject = "SSL Certificate on CADWorker Server $env:computername expires in $expiresIn"
        $body = "The SSL Certificate for FileZilla Server on Instance $env:computername will be " +
                "<b> invalid in $expiresIn days. </b><br><br>Please order a new SSL Certificate for " + 
                "$env:computername . <br><br>This Message was sent by a Scheduled Task."
        Send-MailMessage -To $to -Subject $subject -Body $body -SmtpServer $smtpHost -From $from -BodyAsHtml
     } else {
        "Zertifikat ist noch $expiresIn Tage gültig"
     }

}else{  # Certificate file was not found, so I will send an Error-Mail to operations team 
    $subject = "SSL Certificate on CADWorker Server $env:computername was not found by scheduled task"
    $body = "The SSL Certificate for FileZilla Server on $env:computername that should be checked by " +
            "the checkCertificate Script (Scheduled Task) was not found.<br><br>Maybe the certFile " +
            "Parameter in the Script is not correct or the certificate was moved to another location." +
            "<br>The location where the scripts expects the certificate is: <br><b> $certFile </b>"
    Send-MailMessage -To $to -Subject $subject -Body $body -SmtpServer $smtpHost -From $from -BodyAsHtml
}

Remove last lines from file with shell, bash, csh, zsh

To remove the last X lines of a file, the easiest way is to use head combined with wc -l

# get the output of wc -l (which counts the lines of a file), parse them to a number 
# and extract 3 (the number of lines you want to remove)
philipp@Host% set CMD1="expr `cat longFile.csv | wc -l` - 3"

# now remove last 3 lines by using head and redirect them to your file
philipp@Host% head -n  `$CMD1` Segment5_Contexts.csv > shortFile.csv