* Remove use of deprecated functions from the string module
[mirror/userdir-ldap.git] / ud-userimport
1 #!/usr/bin/env python
2 # -*- mode: python -*-
3
4 #   Copyright (c) 1999       Jason Gunthorpe <jgg@debian.org>
5 #   Copyright (c) 2003       James Troup <troup@debian.org>
6 #   Copyright (c) 2004       Joey Schulze <joey@debian.org>
7 #
8 #   This program is free software; you can redistribute it and/or modify
9 #   it under the terms of the GNU General Public License as published by
10 #   the Free Software Foundation; either version 2 of the License, or
11 #   (at your option) any later version.
12 #
13 #   This program is distributed in the hope that it will be useful,
14 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #   GNU General Public License for more details.
17 #
18 #   You should have received a copy of the GNU General Public License
19 #   along with this program; if not, write to the Free Software
20 #   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21
22 # Imports passwd, shadow and group files into the directory.
23 # You should cleanse the files of anything you do not want to add to the
24 # directory.
25 #
26 # The first step is to call this script to import the passwd file and
27 # create all the new entries. This should be done on an empty freshly 
28 # initialized directory with the rootdn/password set in the server.
29 # The command to execute is
30 #   ldapimport -a -p ~/passwd
31 # The -a tells the script to add all the entries it finds, it should be
32 # used only once.
33 #
34 # The next step is to import the shadow file and group, no clensing need be 
35 # done for 
36 # this as any entries that do not exist will be ignored (silently)
37 #  ldapimport -s /etc/shadow -g /etc/group
38
39
40 import re, time, ldap, getopt, sys;
41 from userdir_ldap import *;
42
43 DoAdd = 0;
44 WritePasses = 1;
45 Passwd = "";
46 Shadow = "";
47 Group = "";
48
49 # This parses a gecos field and returns a tuple containing the new normalized
50 # field and the first, middle and last name of the user. Gecos is formed
51 # in the standard debian manner with 5 feilds seperated by commas
52 def ParseGecos(Field):
53    Gecos = re.split("[,:]",Field);
54    cn = "";
55    mn = "";
56    sn = "";
57    if (len(Gecos) >= 1):
58       (cn,mn,sn) = NameSplit(Gecos[0]);
59
60       # Normalize the gecos field
61       if (len(Gecos) > 5):
62          Gecos = Gecos[0:4];
63       else:
64          while (len(Gecos) < 5):
65             Gecos.append("");
66    else:
67       Gecos = ["","","","",""];
68
69    # Reconstruct the gecos after mauling it
70    Field = Gecos[0] + "," + Gecos[1] + "," + Gecos[2] + "," + \
71            Gecos[3] + "," + Gecos[4];
72    return (Field,cn,mn,sn);
73
74 # Read the passwd file into the database
75 def DoPasswd(l,Passwd):
76    # Read the passwd file and import it
77    Passwd = open(Passwd,"r");
78    Outstanding = 0;
79    while(1):
80       Line = Passwd.readline();
81       if Line == "":
82          break;
83
84       Split = re.split("[:\n]",Line);
85       (Split[4],cn,mn,sn) = ParseGecos(Split[4]);
86       Split[2] = int(Split[2])
87       Split[3] = int(Split[3])
88       Rec = [("uid",Split[0]),
89              ("uidNumber",Split[2]),
90              ("gidNumber",Split[3]),
91              ("gecos",Split[4]),
92              ("homeDirectory",Split[5]),
93              ("loginShell",Split[6]),
94              ("cn",cn),
95              ("sn",sn)];
96
97       # Avoid schema check complaints when mn is empty
98       if (mn):
99           Rec.append(("mn",mn))
100
101       Dn = "uid=" + Split[0] + "," + BaseDn;
102       print "Importing", Dn
103       sys.stdout.flush();
104
105       DoModify = True
106
107       if (DoAdd == 1):
108          try:
109             AddRec = Rec
110             Rec.append(("objectClass", UserObjectClasses))
111             l.add_s(Dn,AddRec)
112             DoModify = False
113
114          except ldap.ALREADY_EXISTS:
115             print "exists",;
116
117       if (DoModify):
118           # Send the modify request
119           ModRec = [(ldap.MOD_REPLACE, k[0], k[1]) for k in Rec]
120           l.modify(Dn,ModRec);
121           Outstanding = Outstanding + 1;
122           Outstanding = FlushOutstanding(l,Outstanding,1);
123           print "done";
124
125    FlushOutstanding(l,Outstanding);
126
127 # Read the shadow file into the database
128 def DoShadow(l,Shadow):
129    # Read the passwd file and import it
130    Shadow = open(Shadow,"r");
131    Outstanding = 0;
132    while(1):
133       Line = Shadow.readline();
134       if Line == "":
135          break;
136
137       Split = re.split("[:\n]",Line);
138       
139       # Ignore system accounts with no password, they do not belong in the
140       # directory.
141       if (Split[1] == 'x' or Split[1] == '*'):
142          print "Ignoring system account,",Split[0];
143          continue;
144
145       for x in range(2,8):
146          Split[x] = int(Split[x])
147
148       Rec = [(ldap.MOD_REPLACE,"shadowLastChange",Split[2]),
149              (ldap.MOD_REPLACE,"shadowMin",Split[3]),
150              (ldap.MOD_REPLACE,"shadowMax",Split[4]),
151              (ldap.MOD_REPLACE,"shadowWarning",Split[5])]
152
153       # Avoid schema violations
154       if (Split[6]):
155          Rec.append((ldap.MOD_REPLACE,"shadowInactive",Split[6]))
156
157       if (Split[7]):
158          Rec.append((ldap.MOD_REPLACE,"shadowExpire",Split[7]))
159
160       if (WritePasses == 1):
161          Rec.append((ldap.MOD_REPLACE,"userPassword","{crypt}"+Split[1]));
162
163       Dn = "uid=" + Split[0] + "," + BaseDn;
164       print "Importing",Dn,
165       sys.stdout.flush();
166
167       # Send the modify request
168       l.modify(Dn,Rec);
169       Outstanding = Outstanding + 1;
170       print "done";
171       Outstanding = FlushOutstanding(l,Outstanding,1);
172    FlushOutstanding(l,Outstanding);
173
174 # Read the group file into the database
175 def DoGroup(l,Group):
176    # Read the passwd file and import it
177    Group = open(Group,"r");
178    Outstanding = 0;
179    while(1):
180       Line = Group.readline();
181       if Line == "":
182          break;
183
184       # Split up the group information
185       Split = re.split("[:\n]",Line);
186       Members = re.split("[, ]*",Split[3]);
187       Split[2] = int(Split[2])
188
189       # Iterate over the membership list and add the membership information
190       # To the directory
191       Rec = [(ldap.MOD_ADD,"supplementaryGid",Split[0])];
192       Counter = 0;
193       for x in Members:
194          if x == "":
195             continue;
196             
197          Dn = "uid=" + x + "," + BaseDn;
198          print "Adding",Dn,"to group",Split[0];
199          Counter = Counter+1;
200
201          # Send the modify request
202          l.modify(Dn,Rec);
203          Outstanding = Outstanding + 1;
204          Outstanding = FlushOutstanding(l,Outstanding,1);
205          
206       if Counter == 0:
207          continue;
208
209       Rec = [(ldap.MOD_REPLACE,"gid",Split[0]),
210              (ldap.MOD_REPLACE,"gidNumber",Split[2])];
211
212       Dn = "gid=" + Split[0] + "," + BaseDn;
213       print "Importing",Dn,
214       sys.stdout.flush();
215
216       # Unfortunately add_s does not take the same args as modify :|
217       if (DoAdd == 1):
218          try:
219             l.add_s(Dn,[("gid",Split[0]),
220                         ("objectClass", GroupObjectClasses)])
221          except ldap.ALREADY_EXISTS:
222             print "exists",;
223
224       # Send the modify request
225       l.modify(Dn,Rec);
226       Outstanding = Outstanding + 1;
227       print ".";
228
229    FlushOutstanding(l,Outstanding);
230
231 # Process options
232 (options, arguments) = getopt.getopt(sys.argv[1:], "ap:s:g:xu:")
233 for (switch, val) in options:
234    if (switch == '-a'):
235       DoAdd = 1;
236    if (switch == '-x'):
237       WritePasses = 0;
238    elif (switch == '-p'):
239       Passwd = val
240    elif (switch == '-s'):
241       Shadow = val
242    elif (switch == '-g'):
243       Group = val
244    elif (switch == '-u'):
245       AdminUser = val
246
247 # Main program starts here
248
249 # Connect to the ldap server
250 l = passwdAccessLDAP(LDAPServer, BaseDn, AdminUser)
251
252 if (Passwd != ""):
253    DoPasswd(l,Passwd);
254
255 if (Shadow != ""):
256    DoShadow(l,Shadow);
257
258 if (Group != ""):
259    DoGroup(l,Group);