Skip to content

Instantly share code, notes, and snippets.

@daurnimator
Forked from RyanSquared/test.py
Created March 18, 2018 01:56
Show Gist options
  • Save daurnimator/1a149d3621d3b6739526a073c6511580 to your computer and use it in GitHub Desktop.
Save daurnimator/1a149d3621d3b6739526a073c6511580 to your computer and use it in GitHub Desktop.
Program to migrate LDAP data to hashbang/userdb
#!/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