-
-
Save daurnimator/1a149d3621d3b6739526a073c6511580 to your computer and use it in GitHub Desktop.
Program to migrate LDAP data to hashbang/userdb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# pylint: disable-all | |
# Search LDAP for all People of hashbang.sh | |
import json | |
import sys | |
import ldap | |
import ldap.resiter | |
import psycopg2 | |
class ResiterLDAPObject(ldap.ldapobject.LDAPObject, | |
ldap.resiter.ResultProcessor): | |
pass | |
ldap_con = ResiterLDAPObject("ldap://ldap.hashbang.sh") | |
ldap_con.start_tls_s() | |
ldap_con.simple_bind_s('cn=provisor,ou=Admin,dc=hashbang,dc=sh', | |
sys.argv[1]) | |
userdb_con = psycopg2.connect("dbname=userdb") | |
cursor = userdb_con.cursor() | |
msg_id = ldap_con.search("dc=hashbang,dc=sh", ldap.SCOPE_SUBTREE, | |
"(uid=*)") | |
insert_users = """ | |
INSERT INTO passwd (uid, name, host, data) | |
VALUES (%s, %s, %s, %s);""" | |
insert_hosts = "INSERT INTO hosts (name, maxusers) VALUES (%s, %s)" | |
hosts = set() | |
for res_type, res_data, res_msgid, res_controls in ldap_con.allresults(msg_id): | |
for dn, entry in res_data: | |
uid, = entry["uidNumber"] | |
name, = entry["uid"] | |
host, = entry["host"] | |
shell, = entry["loginShell"] | |
keys = [key.decode("ascii") for key in entry["sshPublicKey"]] | |
data = json.dumps({"shell": shell.decode("ascii"), "ssh_keys": keys}) | |
values = [value.decode("ascii") for value in [uid, name, host]] | |
if host not in hosts: | |
print("adding host:", host) | |
cursor.execute(insert_hosts, [host.decode("ascii"), 1000]) | |
hosts.add(host) | |
cursor.execute(insert_users, values + [data]) | |
userdb_con.commit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment