Skip to content

Instantly share code, notes, and snippets.

@achimnol
Created June 25, 2012 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save achimnol/2990513 to your computer and use it in GitHub Desktop.
Save achimnol/2990513 to your computer and use it in GitHub Desktop.
Some helper tools for LDAP account management
#! /usr/bin/env python
# --*-- encoding: utf8 --*--
from __future__ import print_function
import pwd, spwd, grp
# TODO: add arguments
if __name__ == '__main__':
processed_userids = set()
for pw_entry in pwd.getpwall():
if pw_entry.pw_name in processed_userids:
continue
if pw_entry.pw_uid < 10000 or pw_entry.pw_uid > 20000:
continue
# TODO: check if the user already exists in LDAP so that 'getent passwd' returns a phantom duplicate.
print("ldapadduser {userid} {userid_numeric} {group}".format(
userid=pw_entry.pw_name,
userid_numeric=pw_entry.pw_uid,
group=grp.getgrgid(pw_entry.pw_gid).gr_name,
))
print("ldapsetpasswd {userid} '{shadow_password}'".format(
userid=pw_entry.pw_name,
shadow_password='{CRYPT}' + spwd.getspnam(pw_entry.pw_name).sp_pwd,
))
processed_userids.add(pw_entry.pw_name)
#! /usr/bin/env python
# --*-- encoding: utf8 --*--
from __future__ import print_function
import os, sys, re
import subprocess
def execute(cmd, *args):
cmdargs = [cmd]
cmdargs.extend(args)
return subprocess.check_output(cmdargs)
OPENLDAP_CONF_DIR = '/etc/ldap/slapd.d'
OPENLDAP_SCHEMA_DIR = OPENLDAP_CONF_DIR + '/cn=config/cn=schema'
OPENLDAP_SCHEMA_REPO = '/etc/ldap/schema'
NEW_SCHEMA_PATH = sys.argv[1]
CURRENT_SCHEMA_NAMES = []
_rx_schema_name = re.compile(r'([^/]+)\.schema$')
_rx_schemaconf_name = re.compile(r'cn=\{[-\d]+\}([^/]+)\.ldif$')
if __name__ == '__main__':
# Get the list of existing schema.
existing_ldifs = os.listdir(OPENLDAP_SCHEMA_DIR)
for filename in sorted(existing_ldifs):
m = re.search(_rx_schemaconf_name, filename)
CURRENT_SCHEMA_NAMES.append(m.group(1))
print('Configured schemas: ' + ', '.join(CURRENT_SCHEMA_NAMES))
NEW_SCHEMA_NAME = _rx_schema_name.search(NEW_SCHEMA_PATH).group(1)
if NEW_SCHEMA_NAME in CURRENT_SCHEMA_NAMES:
print('The same name of schema already exists!')
sys.exit(1)
# Generate a temporary config to load all existing schemas AND the new schema.
execute('mkdir', '-p', '/tmp/ldap')
with open('/tmp/ldap/schema-list.conf', 'w') as f:
for schema_name in CURRENT_SCHEMA_NAMES:
schema_path = os.path.abspath(os.path.join(OPENLDAP_SCHEMA_REPO,
schema_name + '.schema'))
assert os.path.isfile(schema_path)
print('include {0}'.format(schema_path), file=f)
print('include {0}'.format(os.path.abspath(NEW_SCHEMA_PATH)), file=f)
# Generate new schema configurations into a temp directory.
execute('slaptest', '-f', '/tmp/ldap/schema-list.conf', '-F', '/tmp/ldap')
# Overwrite existing configurations.
TEMP_SCHEMA_DIR = '/tmp/ldap/cn=config/cn=schema'
print('Appyling new configuration...')
for filename in os.listdir(TEMP_SCHEMA_DIR):
execute('cp', os.path.join(TEMP_SCHEMA_DIR, filename), OPENLDAP_SCHEMA_DIR)
execute('chmod', '600', os.path.join(OPENLDAP_SCHEMA_DIR, filename))
execute('chown', '-R', 'openldap:openldap', OPENLDAP_SCHEMA_DIR)
execute('rm', '-rf', '/tmp/ldap')
print('Restarting the LDAP server...')
execute('/etc/init.d/slapd', 'restart')
# vim: ts=8 sts=4 sw=4 et
#! /usr/bin/env python
# --*-- encoding: utf8 --*--
from __future__ import print_function
import sys
import ldap
# TODO: add arguments
if __name__ == '__main__':
## first you must open a connection to the server
try:
l = ldap.open("localhost")
# Searching doesn't require a bind in LDAP V3.
# If you're using LDAP v2, set the next line appropriately
# and do a bind as shown in the above example.
# You should set the next option to ldap VERSION2
# if you're using a v2 directory
l.protocol_version = ldap.VERSION3
except ldap.LDAPError, e:
print("CONNECTION ERROR")
print(e)
sys.exit(1)
## The next lines will also need to be changed to support your search requirements and directory
baseDN = "ou=Users,dc=anlab"
searchScope = ldap.SCOPE_SUBTREE
## retrieve all attributes - again adjust to your needs - see documentation for more options
retrieveAttributes = None
searchFilter = "cn=*"
try:
ldap_result_id = l.search(baseDN, searchScope, searchFilter, retrieveAttributes)
result_set = []
while 1:
result_type, result_data = l.result(ldap_result_id, 0)
if (result_data == []):
break
else:
## here you don't have to append to a list
## you could do whatever you want with the individual entry
## The appending to list is just for illustration.
if result_type == ldap.RES_SEARCH_ENTRY:
result_set.append(result_data)
except ldap.LDAPError, e:
print("SEARCH ERROR")
print(e)
sys.exit(1)
for r in result_set:
print(r[0][1]['uid'][0])
# vim: ts=8 sts=4 sw=4 et
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment