4 import string, re, time, ldap, getopt, sys, posix, pwd;
5 from userdir_ldap import *;
6 from userdir_gpg import *;
8 AddressSplit = re.compile("(.*).*<([^@]*)@([^>]*)>");
10 # This tries to search for a free UID. There are two possible ways to do
11 # this, one is to fetch all the entires and pick the highest, the other
12 # is to randomly guess uids until one is free. This uses the formar.
13 # Regrettably ldap doesn't have an integer attribute comparision function
14 # so we can only cut the search down slightly
17 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uidnumber>="+str(HighestUID),["uidnumber"]);
20 ID = int(GetAttr(I,"uidnumber","0"));
23 return HighestUID + 1;
28 (options, arguments) = getopt.getopt(sys.argv[1:], "u:")
29 for (switch, val) in options:
33 print "Accessing LDAP directory as '" + AdminUser + "'";
34 Password = getpass(AdminUser + "'s password: ");
36 # Connect to the ldap server
37 l = ldap.open(LDAPServer);
38 UserDn = "uid=" + AdminUser + "," + BaseDn;
39 l.simple_bind_s(UserDn,Password);
41 # Locate the key of the user we are adding
42 GPGBasicOptions[0] = "--batch" # Permit loading of the config file
44 Foo = raw_input("Who are you going to add (for a GPG search)? ");
48 Keys = GPGKeySearch(Foo);
51 print "Sorry, that search did not turn up any keys";
54 print "Sorry, more than one key was found, please specify the key to use by\nfingerprint:";
60 print "A matching key was found:"
61 GPGPrintKeyInfo(Keys[0]);
64 # Crack up the email address from the key into a best guess
65 # first/middle/last name
66 Match = AddressSplit.match(Keys[0][2]);
68 (cn,mn,sn,email,account) = ('','','','','');
70 (cn,mn,sn) = NameSplit(re.sub('["]','',Match.groups()[0]))
71 email = Match.groups()[1] + '@' + Match.groups()[2];
72 account = Match.groups()[1];
75 gidnumber = str(DefaultGID);
78 # Decide if we should use IDEA encryption
80 while len(Keys[0][1]) < 40:
81 Res = raw_input("Use PGP2.x compatibility [no]? ");
88 # Try to get a uniq account name
91 Res = raw_input("Login account [" + account + "]? ");
94 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + account);
97 Res = raw_input("That account already exists, update [no]? ");
99 # Update mode, fetch the default values from the directory
101 privsub = GetAttr(Attrs[0],"privatesub");
102 gidnumber = GetAttr(Attrs[0],"gidnumber");
103 uidnumber = GetAttr(Attrs[0],"uidnumber");
104 email = GetAttr(Attrs[0],"emailforward");
105 cn = GetAttr(Attrs[0],"cn");
106 sn = GetAttr(Attrs[0],"sn");
107 mn = GetAttr(Attrs[0],"mn");
108 if privsub == None or privsub == "":
112 # Prompt for the first/last name and email address
113 Res = raw_input("First name [" + cn + "]? ");
116 Res = raw_input("Middle name [" + mn + "]? ");
119 Res = raw_input("Last name [" + sn + "]? ");
122 Res = raw_input("Email forwarding address [" + email + "]? ");
126 # Debian-Private subscription
127 Res = raw_input("Subscribe to debian-private (space is none) [" + privsub + "]? ");
132 Res = raw_input("Group ID Number [" + gidnumber + "]? ");
138 uidnumber = GetFreeID(l);
140 # Generate a random password
142 Password = raw_input("User's Password (Enter for random)? ");
145 print "Randomizing and encrypting password"
146 Password = GenPass();
147 Pass = HashPass(Password);
148 print "PASS: ", Password;
150 # Use GPG to encrypt it, pass the fingerprint to ID it
151 CryptedPass = GPGEncrypt("Your new password is '" + Password + "'\n",\
152 "0x"+Keys[0][1],UsePGP2);
154 if CryptedPass == None:
155 raise "Error","Password Encryption failed"
157 Pass = HashPass(Password);
158 CryptedPass = "Your password has been set to the previously agreed value.";
163 # Now we have all the bits of information.
165 FullName = "%s %s %s" % (cn,mn,sn);
167 FullName = "%s %s" % (cn,sn);
168 print "------------";
169 print "Final information collected:"
170 print " %s <%s@%s>:" % (FullName,account,EmailAppend);
171 print " Assigned UID:",uidnumber," GID:", gidnumber;
172 print " Email forwarded to:",email;
173 print " Private Subscription:",privsub;
174 print " GECOS Field: \"%s,,,,\"" % (FullName);
175 print " Login Shell: /bin/bash";
176 print " Key Fingerprint:",Keys[0][1];
177 Res = raw_input("Continue [no]? ");
181 # Initialize the substitution Map
183 Subst["__REALNAME__"] = FullName;
184 Subst["__WHOAMI__"] = pwd.getpwuid(posix.getuid())[0];
185 Subst["__DATE__"] = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
186 Subst["__LOGIN__"] = account;
187 Subst["__PRIVATE__"] = privsub;
188 Subst["__EMAIL__"] = email;
189 Subst["__PASSWORD__"] = CryptedPass;
190 Subst["__LISTPASS__"] = string.strip(open(pwd.getpwuid(posix.getuid())[5]+"/.debian-lists_passwd","r").read());
192 # Generate the LDAP request
193 Rec = [(ldap.MOD_REPLACE,"uid",account),
194 (ldap.MOD_REPLACE,"uidNumber",str(uidnumber)),
195 (ldap.MOD_REPLACE,"gidNumber",str(gidnumber)),
196 (ldap.MOD_REPLACE,"gecos",FullName+",,,,"),
197 (ldap.MOD_REPLACE,"loginShell","/bin/bash"),
198 (ldap.MOD_REPLACE,"keyfingerprint",Keys[0][1]),
199 (ldap.MOD_REPLACE,"cn",cn),
200 (ldap.MOD_REPLACE,"mn",mn),
201 (ldap.MOD_REPLACE,"sn",sn),
202 (ldap.MOD_REPLACE,"emailforward",email),
203 (ldap.MOD_REPLACE,"shadowLastChange",str(int(time.time()/24/60/60))),
204 (ldap.MOD_REPLACE,"shadowMin","0"),
205 (ldap.MOD_REPLACE,"shadowMax","99999"),
206 (ldap.MOD_REPLACE,"shadowWarning","7"),
207 (ldap.MOD_REPLACE,"shadowInactive",""),
208 (ldap.MOD_REPLACE,"shadowExpire","")];
210 Rec.append((ldap.MOD_REPLACE,"privatesub",privsub));
212 Rec.append((ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass));
214 # Submit the modification request
215 Dn = "uid=" + account + "," + BaseDn;
216 print "Updating LDAP directory..",
219 l.add_s(Dn,[("uid",account),
220 ("objectclass","top"),
221 ("objectclass","account"),
222 ("objectclass","posixAccount"),
223 ("objectclass","shadowAccount"),
224 ("objectclass","debiandeveloper")]);
225 except ldap.ALREADY_EXISTS:
228 # Send the modify request
232 # Abort email sends for an update operation
234 print "Account is not new, Not sending mails"
237 # Do the subscription/welcome message
239 print TemplateSubst(Subst,open("templates/list-subscribe","r").read());
241 # Send the Welcome message
242 print "Sending Welcome Email"
243 Reply = TemplateSubst(Subst,open("templates/welcome-message-"+gidnumber,"r").read());
244 Child = posix.popen("/usr/sbin/sendmail -t","w");
245 #Child = posix.popen("cat","w");
247 if Child.close() != None:
248 raise Error, "Sendmail gave a non-zero return code";