Fetching contributors…
Cannot retrieve contributors at this time
executable file 51 lines (37 sloc) 1.4 KB
#!/usr/bin/env python
# This scripts reads SSH public keys from LDAP and
# writes them into /var/cache/ssh/$user.
# All keys are collected in /var/cache/ssh/git for Git login, too
from __future__ import with_statement
import ldap
import os
DESTINATION = '/var/cache/ssh'
LOCAL = ['root', 'nagios']
MERGED = ['git']
def atomic_save(fname, data):
with open(fname + '.new', 'w') as f:
os.chmod(fname + '.new', 0644)
os.rename(fname + '.new', fname)
conn =
code, result = conn.result(, ldap.SCOPE_SUBTREE,
'(sshPublicKey=*)', ('uid', 'sshPublicKey')))
sshkeys = dict([(x[1]['uid'][0], x[1]['sshPublicKey']) for x in result])
# Make sure manually placed keys are not imported from LDAP
for l in LOCAL:
if l in sshkeys:
raise Exception("User %s should not be in LDAP" % l)
delete = set(os.listdir(DESTINATION)).difference(sshkeys).difference(LOCAL)\
for user in delete:
os.unlink(os.path.join(DESTINATION, user))
allkeys = []
for user, keys in sshkeys.iteritems():
allkeys += keys
atomic_save(os.path.join(DESTINATION, user), '\n'.join(keys))
for m in MERGED:
atomic_save(os.path.join(DESTINATION, m), '\n'.join(allkeys))