Use the common routine from userdir_ldap.py which asks for the
[mirror/userdir-ldap.git] / ud-host
1 #!/usr/bin/env python
2 # -*- mode: python -*-
3 # This script is an interactive way to manipulate fields in the LDAP directory.
4 # When run it connects to the directory using the current users ID and fetches
5 # all the attributes for the first machine. It then formats them nicely and
6 # allows the user to change them.
7 #
8 #  Usage: userinfo -a <user> -u <user> -c <user> -r
9 #    -a    Set the authentication user (the user whose password you are
10 #          going to enter)
11 #    -h    Set the host to display
12
13 import string, time, os, pwd, sys, getopt, ldap, crypt, whrandom, readline, copy;
14 from userdir_ldap import *;
15
16 RootMode = 0;
17 AttrInfo = {"description": ["Machine Descr.", 1],
18             "hostname": ["Host names", 2],
19             "status": ["Status", 3],
20             "l": ["Location", 4],
21             "sponsor": ["Sponsors", 5],
22             "distribution": ["Distribution", 6],
23             "access": ["Access", 7],
24             "admin": ["Admin", 8],
25             "architecture": ["Architecture", 9],
26             "machine": ["Machine Hardware", 10],
27             "memory": ["Memory", 11],
28             "disk": ["Disk", 12],
29             "sshRSAHostKey": ["SSH Host Keys", 14],
30             "bandwidth": ["Bandwidth", 15]};
31
32 AttrPrompt = {"description": ["Purpose of the machine"],
33               "hostname": ["The hostnames for the box (ipv4/ipv6)"],
34               "status": ["Blank if Up, explaination if not"],
35               "l": ["Physical location"],
36               "sponsor": ["Sponsors and their URLs"],
37               "distribution": ["The distribution version"],
38               "access": ["all, developer only, restricted"],
39               "admin": ["Admin email address"],
40               "architecture": ["Debian Architecture string"],
41               "machine": ["Hardware description"],
42               "memory": ["Installed RAM"],
43               "disk": ["Disk Space, RAID levels, etc"],
44               "sshRSAHostKey": ["A copy of /etc/ssh/ssh_*host_key.pub"],
45               "bandwidth": ["Available outbound"]};
46
47 # Create a map of IDs to desc,value,attr
48 OrderedIndex = {};
49 for at in AttrInfo.keys():
50    if (AttrInfo[at][1] != 0):
51       OrderedIndex[AttrInfo[at][1]] = [AttrInfo[at][0], "", at];
52 OrigOrderedIndex = copy.deepcopy(OrderedIndex);
53
54 # Print out the automatic time stamp information
55 def PrintModTime(Attrs):
56    Stamp = GetAttr(Attrs,"modifyTimestamp","");
57    if len(Stamp) >= 13:
58       Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
59               int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
60       print "%-24s:" % ("Record last modified on"), time.strftime("%a %d/%m/%Y %X UTC",Time),
61       print "by",ldap.explode_dn(GetAttr(Attrs,"modifiersName"),1)[0];
62
63    Stamp = GetAttr(Attrs,"createTimestamp","");
64    if len(Stamp) >= 13:
65       Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
66               int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
67       print "%-24s:" % ("Record created on"), time.strftime("%a %d/%m/%Y %X UTC",Time);
68
69 # Display all of the attributes in a numbered list
70 def ShowAttrs(Attrs):
71    print;
72    PrintModTime(Attrs);
73
74    for at in Attrs[1].keys():
75       if AttrInfo.has_key(at):
76          if AttrInfo[at][1] == 0:
77             print "      %-18s:" % (AttrInfo[at][0]),
78             for x in Attrs[1][at]:
79                print "'%s'" % (x),
80             print;
81          else:
82             OrderedIndex[AttrInfo[at][1]][1] = Attrs[1][at];
83
84    Keys = OrderedIndex.keys();
85    Keys.sort();
86    for at in Keys:
87       if at < 100 or RootMode != 0:
88          print " %3u) %-18s: " % (at,OrderedIndex[at][0]),
89          for x in OrderedIndex[at][1]:
90             print "'%s'" % (re.sub('[\n\r]','?',x)),
91          print;
92
93 # Change a single attribute
94 def ChangeAttr(Attrs,Attr):
95    if (Attr == "sponsor" or Attr == "hostname" or Attr == "sshRSAHostKey"):
96       return MultiChangeAttr(Attrs,Attr);
97
98    print "Old value: '%s'" % (GetAttr(Attrs,Attr,""));
99    print "Press enter to leave unchanged and a single space to set to empty";
100    NewValue = raw_input("New? ");
101
102    # Empty string
103    if (NewValue == ""):
104       print "Leaving unchanged.";
105       return;
106
107    # Single space designates delete, trap the delete error
108    if (NewValue == " "):
109       print "Deleting.",;
110       try:
111          l.modify_s(HostDn,[(ldap.MOD_DELETE,Attr,None)]);
112       except ldap.NO_SUCH_ATTRIBUTE:
113          pass;
114
115       print;
116       Attrs[1][Attr] = [""];
117       return;
118
119    # Set a new value
120    print "Setting.",;
121    l.modify_s(HostDn,[(ldap.MOD_REPLACE,Attr,NewValue)]);
122    Attrs[1][Attr] = [NewValue];
123    print;
124
125 def MultiChangeAttr(Attrs,Attr):
126    # Make sure that we have an entry
127    if not Attrs[1].has_key(Attr):
128       Attrs[1][Attr] = [];
129
130    Attrs[1][Attr].sort();
131    print "Old values: ",Attrs[1][Attr];
132
133    Mode = string.upper(raw_input("[D]elete or [A]dd? "));
134    if (Mode != 'D' and Mode != 'A'):
135       return;
136
137    NewValue = raw_input("Value? ");
138    # Empty string
139    if (NewValue == ""):
140       print "Leaving unchanged.";
141       return;
142
143    # Delete
144    if (Mode == "D"):
145       print "Deleting.",;
146       try:
147          l.modify_s(HostDn,[(ldap.MOD_DELETE,Attr,NewValue)]);
148       except ldap.NO_SUCH_ATTRIBUTE:
149          print "Failed";
150
151       print;
152       Attrs[1][Attr].remove(NewValue);
153       return;
154
155    # Set a new value
156    print "Setting.",;
157    l.modify_s(HostDn,[(ldap.MOD_ADD,Attr,NewValue)]);
158    Attrs[1][Attr].append(NewValue);
159    print;
160
161 # Main program starts here
162 User = pwd.getpwuid(os.getuid())[0];
163 BindUser = User;
164 # Process options
165 (options, arguments) = getopt.getopt(sys.argv[1:], "nh:a:r")
166 for (switch, val) in options:
167    if (switch == '-h'):
168       Host = val;
169    elif (switch == '-a'):
170       BindUser = val;
171    elif (switch == '-r'):
172       RootMode = 1;
173    elif (switch == '-n'):
174       BindUser = "";
175
176 if (BindUser != ""):
177    l = passwdAccessLDAP(LDAPServer, BaseDn, BindUser)
178 else:
179    l = ldap.open(LDAPServer);
180    l.simple_bind_s("","")
181
182 HBaseDn = "ou=hosts,dc=debian,dc=org";
183 HostDn = "host=" + Host + "," + HBaseDn;
184
185 # Query the server for all of the attributes
186 Attrs = l.search_s(HBaseDn,ldap.SCOPE_ONELEVEL,"host=" + Host);
187 if len(Attrs) == 0:
188    print "Host",Host,"was not found.";
189    sys.exit(0);
190
191 # repeatedly show the account configuration
192 while(1):
193    ShowAttrs(Attrs[0]);
194    if (BindUser == ""):
195       sys.exit(0);
196
197    if RootMode == 1:
198       print "   a) Arbitary Change";
199    print "   n) New Host";
200    print "   d) Delete Host";
201    print "   u) Switch Hosts";
202    print "   x) Exit";
203
204    # Prompt
205    Response = raw_input("Change? ");
206    if (Response == "x" or Response == "X" or Response == "q" or
207        Response == "quit" or Response == "exit"):
208       break;
209
210    # Change who we are looking at
211    if (Response == 'u' or Response == 'U'):
212       NewHost = raw_input("Host? ");
213       if NewHost == "":
214          continue;
215       NAttrs = l.search_s(HBaseDn,ldap.SCOPE_ONELEVEL,"host=" + NewHost);
216       if len(NAttrs) == 0:
217          print "Host",NewHost,"was not found.";
218          continue;
219       Attrs = NAttrs;
220       Host = NewHost;
221       HostDn = "host=" + Host + "," + HBaseDn;
222       OrderedIndex = copy.deepcopy(OrigOrderedIndex);
223       continue;
224
225    # Create a new entry and change to it Change who we are looking at
226    if (Response == 'n' or Response == 'N'):
227       NewHost = raw_input("Host? ");
228       if NewHost == "":
229          continue;
230       NAttrs = l.search_s(HBaseDn,ldap.SCOPE_ONELEVEL,"host=" + NewHost);
231       if len(NAttrs) != 0:
232          print "Host",NewHost,"already exists.";
233          continue;
234       NewHostName = raw_input("Hostname? ");
235       if NewHost == "":
236          continue;
237       Dn = "host=" + NewHost + "," + HBaseDn;
238       l.add_s(Dn,[("host", NewHost),
239                   ("hostname", NewHostName),
240                   ("objectClass", ("top", "debianServer"))]);
241
242       # Switch
243       NAttrs = l.search_s(HBaseDn,ldap.SCOPE_ONELEVEL,"host=" + NewHost);
244       if len(NAttrs) == 0:
245          print "Host",NewHost,"was not found.";
246          continue;
247       Attrs = NAttrs;
248       Host = NewHost;
249       HostDn = "host=" + Host + "," + HBaseDn;
250       OrderedIndex = copy.deepcopy(OrigOrderedIndex);
251       continue;
252
253    # Handle changing an arbitary value
254    if (Response == "a"):
255       Attr = raw_input("Attr? ");
256       ChangeAttr(Attrs[0],Attr);
257       continue;
258
259    if (Response == 'd'):
260       Really = raw_input("Really (type yes)? ");
261       if Really != 'yes':
262           continue;
263       print "Deleting",HostDn;
264       l.delete_s(HostDn);
265       continue;
266
267    # Convert the integer response
268    try:
269       ID = int(Response);
270       if (not OrderedIndex.has_key(ID) or (ID > 100 and RootMode == 0)):
271          raise ValueError;
272    except ValueError:
273       print "Invalid";
274       continue;
275
276    # Print the what to do prompt
277    print "Changing LDAP entry '%s' (%s)" % (OrderedIndex[ID][0],OrderedIndex[ID][2]);
278    print AttrPrompt[OrderedIndex[ID][2]][0];
279    ChangeAttr(Attrs[0],OrderedIndex[ID][2]);