Created
May 1, 2015 12:44
-
-
Save arnobroekhof/491f89881bd29f39f702 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import ldap | |
import os, sys | |
import ConfigParser | |
import logging | |
config_file = '/etc/sysconfig/ssh-ldap' | |
def parse_config(config_file): | |
config = ConfigParser.ConfigParser() | |
if os.path.isfile(config_file): | |
try: | |
config.readfp(open(config_file)) | |
except IOError: | |
logging.warning("Error openening file %s" % config_file) | |
else: | |
logging.warning("File %s doesn't exist" % config_file) | |
exit | |
return config | |
config = parse_config(config_file) | |
logging.basicConfig(filename=config.get('default','log_file'),format='%(asctime)s %(message)s') | |
try: | |
l = ldap.open(config.get('ldap','ldap_host')) | |
l.protocol_version = ldap.VERSION3 | |
except ldap.LDAPError, e: | |
logging.warning(e) | |
def check_args(): | |
username = None | |
if len(sys.argv) > 1: | |
username = sys.argv[1] | |
return username | |
username = check_args() | |
if username == None: | |
logging.warning("No username given") | |
exit | |
baseDN = config.get('ldap','ldap_basedn') | |
searchScope = ldap.SCOPE_SUBTREE | |
retrieveAttributes = [ config.get('ldap','ldap_ssh_attribute'), ] | |
searchFilter = "%s=%s" % ( config.get('ldap','ldap_user_identifier'), username) | |
def search_ldap(baseDN, searchScope, retrieveAttributes, searchFilter): | |
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: | |
if result_type == ldap.RES_SEARCH_ENTRY: | |
result_set.append(result_data) | |
return result_set | |
except ldap.LDAPError, e: | |
logging.warning(e) | |
user_keys = search_ldap(baseDN, searchScope, retrieveAttributes, searchFilter) | |
if not user_keys == None: | |
for user_key in user_keys: | |
for key in user_key[0][1].get('sshPublicKey'): | |
logging.info('retrieved keys for %s' % username ) | |
print key | |
else: | |
logging.warning("No keys found for %s" % username ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment