Import from samosa: Provide a space for proper questioning
[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 def GetFreeID(l):
14    HighestUID = 1000;
15    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,
16                       "gidNumber>="+str(HighestUID),["gidNumber"]);
17    HighestUID = 0;
18    for I in Attrs:
19       ID = int(GetAttr(I,"gidNumber","0"));
20       if ID > HighestUID and ID < 60000:
21          HighestUID = ID;
22    return HighestUID + 1;
23
24 # Main starts here
25 AdminUser = pwd.getpwuid(os.getuid())[0];
26
27 # Process options
28 ForceMail = 0;
29 OldGPGKeyRings = GPGKeyRings;
30 userdir_gpg.GPGKeyRings = [];
31 (options, arguments) = getopt.getopt(sys.argv[1:], "u:")
32 for (switch, val) in options:
33    if (switch == '-u'):
34       AdminUser = val;
35
36 print "Accessing LDAP directory as '" + AdminUser + "'";
37 Password = getpass(AdminUser + "'s password: ");
38
39 # Connect to the ldap server
40 l = ldap.open(LDAPServer);
41 UserDn = "uid=" + AdminUser + "," + BaseDn;
42 l.simple_bind_s(UserDn,Password);
43
44 while 1:
45    Group = raw_input("Group name? ");
46    if Group == "":
47       sys.exit(1);
48
49    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"gid=" + Group);
50    if len(Attrs) == 0:
51       break;
52    print "Group already exists";
53
54 Id = GetFreeID(l);
55 print "Create group %s ID = %d"%(Group,Id);
56
57 # Submit the add request
58 Dn = "gid=" + Group + "," + BaseDn;
59 print "Updating LDAP directory..",
60 sys.stdout.flush();
61 l.add_s(Dn,[("gid",Group),
62             ("gidNumber",str(Id)),
63             ("objectclass","top"),
64             ("objectclass","posixGroup")]);