Skip to content

Instantly share code, notes, and snippets.

@bendavis78
Created August 31, 2018 04:27
Show Gist options
  • Save bendavis78/6d6d7345b46a6503151d946f518296d8 to your computer and use it in GitHub Desktop.
Save bendavis78/6d6d7345b46a6503151d946f518296d8 to your computer and use it in GitHub Desktop.
Python script for sshd's AuthorizedKeysCommand to get pubkeys from ldap
#!/usr/bin/env python3
import ldap
import os
import pwd
import sys
HOST = 'ldap://ldap.example.com'
BASE = 'dc=example,dc=ocom'
# Set a short timeout since this should be run on localhost
TIMEOUT = 5.0
# get the home dir for the given uid
uid = int(sys.argv[1])
userhome = pwd.getpwuid(uid).pw_dir
# Get the authorized-keys in user's homedir first
authKeysFile = os.path.join(userhome, 'ssh', 'authorized-keys')
if userhome and os.path.exists(authKeysFile):
with open(os.path.join(userhome, '.ssh', 'authorized-keys')) as authKeys:
print(authKeysFile.read())
# Set up the ldap connection
binddn = 'cn=pubkeys,ou=system,' + BASE
bindpw = open('/etc/ldap-pubkeys.secret').read().strip()
conn = ldap.initialize(HOST)
conn.set_option(ldap.OPT_NETWORK_TIMEOUT, TIMEOUT)
conn.simple_bind_s(binddn, bindpw)
# Get the user's ssh public key
query = '(&(objectClass=ldapPublicKey)(uidNumber={}))'.format(uid)
results = conn.search_s(BASE, ldap.SCOPE_SUBTREE, query, ['sshPublicKey'])
for dn, attrs in results:
if attrs.get('sshPublicKey'):
print(attrs['sshPublicKey'][0].decode('utf-8').strip())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment