LoginSignup
7
6

More than 5 years have passed since last update.

ActiveDirectoryをldapsearchで覗くとき用のフィルタ

Last updated at Posted at 2016-07-22

ldapsearchを使ってActiveDirectoryのユーザオブジェクトやコンピュータオブジェクトのプロパティを見ることができます。

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

ただし、これだと以下のような問題があり、まともに見ることができません。

  • 属性値に2バイト文字が入っているとBase64エンコードされた文字列が表示される
  • 日付時刻が18桁の数値で表示される
  • userCertificateなど不要な属性も表示されてしまう

これらの問題を解決するためのフィルタを書いてみました。
こんな感じのシェルスクリプトで呼ぶと便利かと思います。
※上4行はご自身の環境に合わせて書き換えてください。

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()
# Base64な行を連結
r = re.compile('\n ', re.MULTILINE)
f = re.sub(r, '', input_file)
input = f.split('\n')

# 表示しないレコード
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):
  # 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
7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6