1 |
#!/usr/bin/python |
2 |
|
3 |
import sys |
4 |
import os |
5 |
import random |
6 |
|
7 |
try: |
8 |
import ldap |
9 |
except ImportError, e: |
10 |
print "Please install python-ldap before running this program" |
11 |
sys.exit(1) |
12 |
|
13 |
basedn="<%= dc_suffix %>" |
14 |
peopledn="ou=people,%s" % basedn |
15 |
uris=['ldap://ldap.<%= domain %>'] |
16 |
random.shuffle(uris) |
17 |
uri = " ".join(uris) |
18 |
timeout=5 |
19 |
binddn="cn=<%= fqdn %>,ou=Hosts,%s" % basedn |
20 |
pwfile="<%= ldap_pwfile %>" |
21 |
# filter out disabled accounts also |
22 |
# too bad uidNumber doesn't support >= filters |
23 |
filter="(&(objectClass=inetOrgPerson)(objectClass=ldapPublicKey)(objectClass=posixAccount)(sshPublicKey=*))" |
24 |
keypathprefix="<%= pubkeys_directory %>" |
25 |
|
26 |
def usage(): |
27 |
print "%s" % sys.argv[0] |
28 |
print |
29 |
print "Will fetch all enabled user accounts under %s" % peopledn |
30 |
print "with ssh keys in them and write each one to" |
31 |
print "%s/<login>/authorized_keys" % keypathprefix |
32 |
print |
33 |
print "This script is intented to be run from cron as root" |
34 |
print |
35 |
|
36 |
def get_pw(pwfile): |
37 |
try: |
38 |
f = open(pwfile, 'r') |
39 |
except IOError, e: |
40 |
print "Error while reading password file, aborting" |
41 |
print e |
42 |
sys.exit(1) |
43 |
pw = f.readline().strip() |
44 |
f.close() |
45 |
return pw |
46 |
|
47 |
def write_keys(keys, user, uid, gid): |
48 |
try: |
49 |
os.makedirs("%s/%s" % (keypathprefix,user), 0700) |
50 |
except: |
51 |
pass |
52 |
keyfile = "%s/%s/authorized_keys" % (keypathprefix,user) |
53 |
f = open(keyfile, 'w') |
54 |
for key in keys: |
55 |
f.write(key.strip() + "\n") |
56 |
f.close() |
57 |
os.chmod(keyfile, 0600) |
58 |
os.chown(keyfile, uid, gid) |
59 |
os.chmod("%s/%s" % (keypathprefix,user), 0700) |
60 |
os.chown("%s/%s" % (keypathprefix,user), uid, gid) |
61 |
|
62 |
if len(sys.argv) != 1: |
63 |
usage() |
64 |
sys.exit(1) |
65 |
|
66 |
bindpw = get_pw(pwfile) |
67 |
|
68 |
try: |
69 |
ld = ldap.initialize(uri) |
70 |
ld.set_option(ldap.OPT_NETWORK_TIMEOUT, timeout) |
71 |
ld.start_tls_s() |
72 |
ld.bind_s(binddn, bindpw) |
73 |
res = ld.search_s(peopledn, ldap.SCOPE_ONELEVEL, filter, ['uid','sshPublicKey','uidNumber','gidNumber']) |
74 |
try: |
75 |
os.makedirs(keypathprefix, 0701) |
76 |
except: |
77 |
pass |
78 |
for result in res: |
79 |
dn, entry = result |
80 |
# skip possible system users |
81 |
if int(entry['uidNumber'][0]) < 500: |
82 |
continue |
83 |
write_keys(entry['sshPublicKey'], entry['uid'][0], int(entry['uidNumber'][0]), int(entry['gidNumber'][0])) |
84 |
ld.unbind_s() |
85 |
except Exception, e: |
86 |
print "Error" |
87 |
raise |
88 |
|
89 |
sys.exit(0) |
90 |
|
91 |
|
92 |
# vim:ts=4:sw=4:et:ai:si |