Import from samosa: The LDAP server in woody doesn't provide an
[mirror/userdir-ldap.git] / ud-groupadd
1 #!/usr/bin/env python
2 # -*- mode: python -*-
3
4 import string, re, time, ldap, getopt, sys, os, pwd;
5 from userdir_ldap import *;
6 from userdir_gpg import *;
7
8 # This tries to search for a free UID. There are two possible ways to do
9 # this, one is to fetch all the entires and pick the highest, the other
10 # is to randomly guess uids until one is free. This uses the former.
11 # Regrettably ldap doesn't have an integer attribute comparision function
12 # so we can only cut the search down slightly
13
14 # [JT] This is broken with Woody LDAP and the Schema; for now just
15 #      search through all GIDs.
16 def GetFreeID(l):
17    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,
18                       "gidNumber=*",["gidNumber"]);
19    HighestUID = 0;
20    for I in Attrs:
21       ID = int(GetAttr(I,"gidNumber","0"));
22       if ID > HighestUID and ID < 60000:
23          HighestUID = ID;
24    return HighestUID + 1;
25
26 # Main starts here
27 AdminUser = pwd.getpwuid(os.getuid())[0];
28
29 # Process options
30 ForceMail = 0;
31 OldGPGKeyRings = GPGKeyRings;
32 userdir_gpg.GPGKeyRings = [];
33 (options, arguments) = getopt.getopt(sys.argv[1:], "u:")
34 for (switch, val) in options:
35    if (switch == '-u'):
36       AdminUser = val;
37
38 print "Accessing LDAP directory as '" + AdminUser + "'";
39 Password = getpass(AdminUser + "'s password: ");
40
41 # Connect to the ldap server
42 l = ldap.open(LDAPServer);
43 UserDn = "uid=" + AdminUser + "," + BaseDn;
44 l.simple_bind_s(UserDn,Password);
45
46 while 1:
47    Group = raw_input("Group name? ");
48    if Group == "":
49       sys.exit(1);
50
51    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"gid=" + Group);
52    if len(Attrs) == 0:
53       break;
54    print "Group already exists";
55
56 Id = GetFreeID(l);
57 print "Create group %s ID = %d"%(Group,Id);
58
59 # Submit the add request
60 Dn = "gid=" + Group + "," + BaseDn;
61 print "Updating LDAP directory..",
62 sys.stdout.flush();
63 l.add_s(Dn,[("gid",Group),
64             ("gidNumber",str(Id)),
65             ("objectClass",("top", "debianGroup"))]);