[PYTHON] Filter for looking into Active Directory with ldapsearch

You can use ldapsearch to see the properties of user and computer objects in Active Directory.

ldapsearch -LLL -x -D username -w password -h DCNAME -b dc=contoso,dc=local "(anr=Yamada)"

However, this has the following problems and cannot be seen properly.

--Base64 encoded strings are displayed when double-byte characters are included in the attribute value --Date and time are displayed as 18-digit numbers --Unnecessary attributes such as userCertificate are also displayed

I wrote a filter to solve these problems. I think it would be convenient to call it with a shell script like this.

dc=dccomputername
user=ldapuser
pass=ldapuserpassword
base="dc=contoso,dc=local"
disp="cn displayName company telephoneNumber physicalDeliveryOfficeName description title mail sAMAccountName"

ldapsearch -LLL -x -D $user -w $pass -h $dc -b $base "(anr=$1)" $disp | adfilter.py

adfilter.py


#!/usr/bin/env python
#coding: utf-8

import os, sys
import datetime
import re
import base64

input_file = sys.stdin.read()
#Concatenate Base64 lines
r = re.compile('\n ', re.MULTILINE)
f = re.sub(r, '', input_file)
input = f.split('\n')

#Records not to display
ignore_record = ('^objectGUID','^objectSid','^userParameters','^logonHours','^userCertificate','^mSMQSignCertificates','^mSMQDigests')
re_ignore_record = re.compile(r'\b(' + ('|'.join(ignore_record)) + r')\b')

# ActiveDirectory datetime record
ad_date_value = (
  '^badPasswordTime', '^lastLogon', '^pwdLastSet', '^lastLogonTimestamp', '^accountExpires'
)
re_ad_date_value = re.compile(r'\b(' + ('|'.join(ad_date_value)) + r')\b')

for line in input:
  if line and re_ignore_record.search(line):
    #print line
    pass

  elif re.search(r'::',line):
  #Decode Base64
    try:
      japanese = line.split(":: ")
      b64_string = japanese[1]
      decoded_string = base64.b64decode(b64_string)
      print '%s:: %s' % (japanese[0], decoded_string)
    except:
      print line

  elif line and re_ad_date_value.search(line):
    try:
      ldap_attributes = line.split(": ")
      ldap_adtime = int(ldap_attributes[1])
      ldap_unixtime = (ldap_adtime/10000000)-11644473600
      d = datetime.datetime.fromtimestamp(ldap_unixtime)
      ldap_datetime = d.strftime("%Y-%m-%d %H:%M:%S")
      print '%s: %s' % (ldap_attributes[0], ldap_datetime)
    except:
      print line
      # pass

  else:
    print line

Recommended Posts

Filter for looking into Active Directory with ldapsearch
Join CentOS 8.3 with SSSD to Active Directory
Build a python environment for each directory with pyenv-virtualenv