Permalink
Browse files

Add ldap-sshkeys

  • Loading branch information...
1 parent 29b2bb4 commit 2d8fffa14cbba5019038485325170f4c78a3f271 @mxey mxey committed Nov 18, 2012
Showing with 49 additions and 0 deletions.
  1. +49 −0 ldap-sshkeys
View
@@ -0,0 +1,49 @@
+#!/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
+
+LDAP_SERVER='backend.chaosdorf.de'
+LDAP_BASE='dc=chaosdorf,dc=de'
+DESTINATION = '/var/cache/ssh'
+LOCAL = ['root', 'nagios']
+MERGED = ['git']
+
+def atomic_save(fname, data):
+ with open(fname + '.new', 'w') as f:
+ f.write(data)
+ os.rename(fname + '.new', fname)
+
+conn = ldap.open(LDAP_SERVER)
+conn.simple_bind_s()
+code, result = conn.result(conn.search(LDAP_BASE, 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)\
+ .difference(MERGED)
+
+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))
+
+
+conn.unbind_s()

0 comments on commit 2d8fffa

Please sign in to comment.