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