4ba05719ff238ce6aded1f34923c3adecbedb731
[mirror/userdir-ldap.git] / ud-host
1 #!/usr/bin/env python
2 # -*- mode: python -*-
3
4 #   Copyright (c) 2000-2001  Jason Gunthorpe <jgg@debian.org>
5 #   Copyright (c) 2001       Ryan Murray <rmurray@debian.org>
6 #   Copyright (c) 2003       James Troup <troup@debian.org>
7 #   Copyright (c) 2004-2005  Joey Schulze <joey@infodrom.org>
8 #
9 #   This program is free software; you can redistribute it and/or modify
10 #   it under the terms of the GNU General Public License as published by
11 #   the Free Software Foundation; either version 2 of the License, or
12 #   (at your option) any later version.
13 #
14 #   This program is distributed in the hope that it will be useful,
15 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
16 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 #   GNU General Public License for more details.
18 #
19 #   You should have received a copy of the GNU General Public License
20 #   along with this program; if not, write to the Free Software
21 #   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22
23 # This script is an interactive way to manipulate fields in the LDAP directory.
24 # When run it connects to the directory using the current users ID and fetches
25 # all the attributes for the first machine. It then formats them nicely and
26 # allows the user to change them.
27 #
28 #  Usage: userinfo -a <user> -u <user> -c <user> -r
29 #    -a    Set the authentication user (the user whose password you are
30 #          going to enter)
31 #    -h    Set the host to display
32 #    -l    list all hosts and their status
33 #    -f    list all SSH fingerprints
34
35 import string, time, os, pwd, sys, getopt, ldap, crypt, readline, copy;
36 from tempfile import mktemp
37 from os import O_CREAT, O_EXCL, O_WRONLY
38 from userdir_ldap import *;
39
40 RootMode = 0;
41 AttrInfo = {"description": ["Machine Descr.", 1],
42             "hostname": ["Host names", 2],
43             "status": ["Status", 3],
44             "l": ["Location", 4],
45             "sponsor": ["Sponsors", 5],
46             "distribution": ["Distribution", 6],
47             "access": ["Access", 7],
48             "admin": ["Admin", 8],
49             "architecture": ["Architecture", 9],
50             "machine": ["Machine Hardware", 10],
51             "memory": ["Memory", 11],
52             "disk": ["Disk", 12],
53             "sshRSAHostKey": ["SSH Host Keys", 14],
54             "bandwidth": ["Bandwidth", 15]};
55
56 AttrPrompt = {"description": ["Purpose of the machine"],
57               "hostname": ["The hostnames for the box (ipv4/ipv6)"],
58               "status": ["Blank if Up, explaination if not"],
59               "l": ["Physical location"],
60               "sponsor": ["Sponsors and their URLs"],
61               "distribution": ["The distribution version"],
62               "access": ["all, developer only, restricted"],
63               "admin": ["Admin email address"],
64               "architecture": ["Debian Architecture string"],
65               "machine": ["Hardware description"],
66               "memory": ["Installed RAM"],
67               "disk": ["Disk Space, RAID levels, etc"],
68               "sshRSAHostKey": ["A copy of /etc/ssh/ssh_*host_key.pub"],
69               "bandwidth": ["Available outbound"]};
70
71 # Create a map of IDs to desc,value,attr
72 OrderedIndex = {};
73 for at in AttrInfo.keys():
74    if (AttrInfo[at][1] != 0):
75       OrderedIndex[AttrInfo[at][1]] = [AttrInfo[at][0], "", at];
76 OrigOrderedIndex = copy.deepcopy(OrderedIndex);
77
78 # Print out the automatic time stamp information
79 def PrintModTime(Attrs):
80    Stamp = GetAttr(Attrs,"modifyTimestamp","");
81    if len(Stamp) >= 13:
82       Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
83               int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
84       print "%-24s:" % ("Record last modified on"), time.strftime("%a %d/%m/%Y %X UTC",Time),
85       print "by",ldap.explode_dn(GetAttr(Attrs,"modifiersName"),1)[0];
86
87    Stamp = GetAttr(Attrs,"createTimestamp","");
88    if len(Stamp) >= 13:
89       Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
90               int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
91       print "%-24s:" % ("Record created on"), time.strftime("%a %d/%m/%Y %X UTC",Time);
92
93 # Display all of the attributes in a numbered list
94 def ShowAttrs(Attrs):
95    print;
96    PrintModTime(Attrs);
97
98    for at in Attrs[1].keys():
99       if AttrInfo.has_key(at):
100          if AttrInfo[at][1] == 0:
101             print "      %-18s:" % (AttrInfo[at][0]),
102             for x in Attrs[1][at]:
103                print "'%s'" % (x),
104             print;
105          else:
106             OrderedIndex[AttrInfo[at][1]][1] = Attrs[1][at];
107
108    Keys = OrderedIndex.keys();
109    Keys.sort();
110    for at in Keys:
111       if at < 100 or RootMode != 0:
112          print " %3u) %-18s: " % (at,OrderedIndex[at][0]),
113          for x in OrderedIndex[at][1]:
114             print "'%s'" % (re.sub('[\n\r]','?',x)),
115          print;
116
117 def Overview(Attrs):
118    """Display a one-line overview for a given host"""
119    for i in ['host','architecture','distribution','access','status']:
120       if i not in Attrs[1].keys():
121          Attrs[1][i] = ['']
122    print "%-12s  %-10s  %-38s  %-25s %s" % (\
123       Attrs[1]['host'][0], \
124       Attrs[1]['architecture'][0], \
125       Attrs[1]['distribution'][0], \
126       Attrs[1]['access'][0], \
127       Attrs[1]['status'][0])
128
129 # Change a single attribute
130 def ChangeAttr(Attrs,Attr):
131    if (Attr == "sponsor" or Attr == "sshRSAHostKey"):
132       return MultiChangeAttr(Attrs,Attr);
133
134    print "Old value: '%s'" % (GetAttr(Attrs,Attr,""));
135    print "Press enter to leave unchanged and a single space to set to empty";
136    NewValue = raw_input("New? ");
137
138    # Empty string
139    if (NewValue == ""):
140       print "Leaving unchanged.";
141       return;
142
143    # Single space designates delete, trap the delete error
144    if (NewValue == " "):
145       print "Deleting.",;
146       try:
147          l.modify_s(HostDn,[(ldap.MOD_DELETE,Attr,None)]);
148       except ldap.NO_SUCH_ATTRIBUTE:
149          pass;
150
151       print;
152       Attrs[1][Attr] = [""];
153       return;
154
155    # Set a new value
156    print "Setting.",;
157    l.modify_s(HostDn,[(ldap.MOD_REPLACE,Attr,NewValue)]);
158    Attrs[1][Attr] = [NewValue];
159    print;
160
161 def MultiChangeAttr(Attrs,Attr):
162    # Make sure that we have an entry
163    if not Attrs[1].has_key(Attr):
164       Attrs[1][Attr] = [];
165
166    Attrs[1][Attr].sort();
167    print "Old values: ",Attrs[1][Attr];
168
169    Mode = string.upper(raw_input("[D]elete or [A]dd? "));
170    if (Mode != 'D' and Mode != 'A'):
171       return;
172
173    NewValue = raw_input("Value? ");
174    # Empty string
175    if (NewValue == ""):
176       print "Leaving unchanged.";
177       return;
178
179    # Delete
180    if (Mode == "D"):
181       print "Deleting.",;
182       try:
183          l.modify_s(HostDn,[(ldap.MOD_DELETE,Attr,NewValue)]);
184       except ldap.NO_SUCH_ATTRIBUTE:
185          print "Failed";
186
187       print;
188       Attrs[1][Attr].remove(NewValue);
189       return;
190
191    # Set a new value
192    print "Setting.",;
193    l.modify_s(HostDn,[(ldap.MOD_ADD,Attr,NewValue)]);
194    Attrs[1][Attr].append(NewValue);
195    print;
196
197 def CalcTempFile():
198    unique = 0
199    while unique == 0:
200       name = mktemp()
201       try:
202          fd = os.open(name, O_CREAT | O_EXCL | O_WRONLY, 0600)
203       except OSError:
204          continue
205       os.close(fd)
206       unique = 1
207    return name
208
209
210 # Main program starts here
211 User = pwd.getpwuid(os.getuid())[0];
212 BindUser = User;
213 ListMode = 0
214 FingerPrints = 0
215 Host = None
216 # Process options
217 try:
218    (options, arguments) = getopt.getopt(sys.argv[1:], "nh:a:rlf")
219 except getopt.GetoptError, data:
220    print data
221    sys.exit(1)
222
223 for (switch, val) in options:
224    if (switch == '-h'):
225       Host = val;
226    elif (switch == '-a'):
227       BindUser = val;
228    elif (switch == '-r'):
229       RootMode = 1;
230    elif (switch == '-n'):
231       BindUser = "";
232    elif (switch == '-l'):
233       BindUser = "";
234       ListMode = 1
235    elif (switch == '-f'):
236       BindUser = "";
237       FingerPrints = 1
238
239 if (BindUser != ""):
240    l = passwdAccessLDAP(LDAPServer, BaseDn, BindUser)
241 else:
242    l = ldap.open(LDAPServer);
243    l.simple_bind_s("","")
244
245 HBaseDn = HostBaseDn
246
247 if ListMode == 1:
248    Attrs = l.search_s(HBaseDn,ldap.SCOPE_ONELEVEL,"host=*")
249    hosts = []
250    for hAttrs in Attrs:
251       hosts.append(hAttrs[1]['host'][0])
252    hosts.sort()
253
254    print "%-12s  %-10s  %-38s  %-25s %s" % ("Host name","Arch","Distribution","Access","Status")
255    print "-"*115
256    for host in hosts:
257       for hAttrs in Attrs:
258          if host == hAttrs[1]['host'][0]:
259             Overview(hAttrs)
260    sys.exit(0)
261 elif FingerPrints == 1:
262    if Host is not None:
263       Attrs = l.search_s(HBaseDn,ldap.SCOPE_ONELEVEL,"host=" + Host)
264    else:
265       Attrs = l.search_s(HBaseDn,ldap.SCOPE_ONELEVEL,"host=*")
266    hosts = []
267    for hAttrs in Attrs:
268       hosts.append(hAttrs[1]['host'][0])
269    hosts.sort()
270
271    tmpfile = CalcTempFile()
272    for host in hosts:
273       for hAttrs in Attrs:
274          if host == hAttrs[1]['host'][0]:
275             if 'sshRSAHostKey' in hAttrs[1].keys():
276                for key in hAttrs[1]['sshRSAHostKey']:
277                   tmp = open(tmpfile, 'w')
278                   tmp.write(key + '\n')
279                   tmp.close()
280                   fp = os.popen('/usr/bin/ssh-keygen -l -f ' + tmpfile, "r")
281                   input = fp.readline()
282                   fp.close()
283                   fingerprint = input.split(' ')
284                   print "%s %s root@%s" % (fingerprint[0], fingerprint[1], host)
285    os.unlink(tmpfile)
286    sys.exit(0)
287
288 HostDn = "host=" + Host + "," + HBaseDn;
289
290 # Query the server for all of the attributes
291 Attrs = l.search_s(HBaseDn,ldap.SCOPE_ONELEVEL,"host=" + Host);
292 if len(Attrs) == 0:
293    print "Host",Host,"was not found.";
294    sys.exit(0);
295
296 # repeatedly show the account configuration
297 while(1):
298    ShowAttrs(Attrs[0]);
299    if (BindUser == ""):
300       sys.exit(0);
301
302    if RootMode == 1:
303       print "   a) Arbitary Change";
304    print "   n) New Host";
305    print "   d) Delete Host";
306    print "   u) Switch Hosts";
307    print "   x) Exit";
308
309    # Prompt
310    Response = raw_input("Change? ");
311    if (Response == "x" or Response == "X" or Response == "q" or
312        Response == "quit" or Response == "exit"):
313       break;
314
315    # Change who we are looking at
316    if (Response == 'u' or Response == 'U'):
317       NewHost = raw_input("Host? ");
318       if NewHost == "":
319          continue;
320       NAttrs = l.search_s(HBaseDn,ldap.SCOPE_ONELEVEL,"host=" + NewHost);
321       if len(NAttrs) == 0:
322          print "Host",NewHost,"was not found.";
323          continue;
324       Attrs = NAttrs;
325       Host = NewHost;
326       HostDn = "host=" + Host + "," + HBaseDn;
327       OrderedIndex = copy.deepcopy(OrigOrderedIndex);
328       continue;
329
330    # Create a new entry and change to it Change who we are looking at
331    if (Response == 'n' or Response == 'N'):
332       NewHost = raw_input("Host? ");
333       if NewHost == "":
334          continue;
335       NAttrs = l.search_s(HBaseDn,ldap.SCOPE_ONELEVEL,"host=" + NewHost);
336       if len(NAttrs) != 0:
337          print "Host",NewHost,"already exists.";
338          continue;
339       NewHostName = raw_input("Hostname? ");
340       if NewHost == "":
341          continue;
342       Dn = "host=" + NewHost + "," + HBaseDn;
343       l.add_s(Dn,[("host", NewHost),
344                   ("hostname", NewHostName),
345                   ("objectClass", ("top", "debianServer"))]);
346
347       # Switch
348       NAttrs = l.search_s(HBaseDn,ldap.SCOPE_ONELEVEL,"host=" + NewHost);
349       if len(NAttrs) == 0:
350          print "Host",NewHost,"was not found.";
351          continue;
352       Attrs = NAttrs;
353       Host = NewHost;
354       HostDn = "host=" + Host + "," + HBaseDn;
355       OrderedIndex = copy.deepcopy(OrigOrderedIndex);
356       continue;
357
358    # Handle changing an arbitary value
359    if (Response == "a"):
360       Attr = raw_input("Attr? ");
361       ChangeAttr(Attrs[0],Attr);
362       continue;
363
364    if (Response == 'd'):
365       Really = raw_input("Really (type yes)? ");
366       if Really != 'yes':
367           continue;
368       print "Deleting",HostDn;
369       l.delete_s(HostDn);
370       continue;
371
372    # Convert the integer response
373    try:
374       ID = int(Response);
375       if (not OrderedIndex.has_key(ID) or (ID > 100 and RootMode == 0)):
376          raise ValueError;
377    except ValueError:
378       print "Invalid";
379       continue;
380
381    # Print the what to do prompt
382    print "Changing LDAP entry '%s' (%s)" % (OrderedIndex[ID][0],OrderedIndex[ID][2]);
383    print AttrPrompt[OrderedIndex[ID][2]][0];
384    ChangeAttr(Attrs[0],OrderedIndex[ID][2]);