Add dnsTTL host attribute to override the zone default TTL for A and AAAA records...
[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 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             "physicalHost": ["Physical Host", 13],
54             "sshRSAHostKey": ["SSH Host Keys", 14],
55             "bandwidth": ["Bandwidth", 15],
56             "purpose": ["Purposes", 16],
57             "allowedGroups": ["Groups", 17],
58             "exportOptions": ["Export-Opts", 18],
59             "ipHostNumber": ["IP Address", 19],
60             "mXRecord": ["MXRecord", 20],
61             "dnsTTL": ["dnsTTL", 21],
62             "sshdistAuthKeysHost": ["extra authkeys ip", 22],
63             }
64
65 AttrPrompt = {"description": ["Purpose of the machine"],
66               "hostname": ["The hostnames for the box (ipv4/ipv6)"],
67               "status": ["Blank if Up, explaination if not"],
68               "l": ["Physical location"],
69               "sponsor": ["Sponsors and their URLs"],
70               "distribution": ["The distribution version"],
71               "access": ["all, developer only, restricted"],
72               "admin": ["Admin email address"],
73               "architecture": ["Debian Architecture string"],
74               "machine": ["Hardware description"],
75               "memory": ["Installed RAM"],
76               "disk": ["Disk Space, RAID levels, etc"],
77               "physicalHost": ["The box hosting this virtual server"],
78               "sshRSAHostKey": ["A copy of /etc/ssh/ssh_*host_key.pub"],
79               "bandwidth": ["Available outbound"],
80               "purpose": ["The purposes of this host"],
81               "allowedGroups": ["allowed Groups on this host"],
82               "exportOptions": ["additional export options"],
83               "ipHostNumber": ["IP Addresses(es) of the machine"],
84               "mXRecord": ["Mail Exchanger for this machine"],
85               "dnsTTL": ["dns TTL value"],
86               "sshdistAuthKeysHost": ["additional hosts for sshdist's authkeys file"],
87               };
88
89 # Create a map of IDs to desc,value,attr
90 OrderedIndex = {};
91 for at in AttrInfo.keys():
92    if (AttrInfo[at][1] != 0):
93       OrderedIndex[AttrInfo[at][1]] = [AttrInfo[at][0], "", at];
94 OrigOrderedIndex = copy.deepcopy(OrderedIndex);
95
96 # Print out the automatic time stamp information
97 def PrintModTime(Attrs):
98    Stamp = GetAttr(Attrs,"modifyTimestamp","");
99    if len(Stamp) >= 13:
100       Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
101               int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
102       print "%-24s:" % ("Record last modified on"), time.strftime("%a %d/%m/%Y %X UTC",Time),
103       print "by",ldap.explode_dn(GetAttr(Attrs,"modifiersName"),1)[0];
104
105    Stamp = GetAttr(Attrs,"createTimestamp","");
106    if len(Stamp) >= 13:
107       Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
108               int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
109       print "%-24s:" % ("Record created on"), time.strftime("%a %d/%m/%Y %X UTC",Time);
110
111 # Display all of the attributes in a numbered list
112 def ShowAttrs(Attrs):
113    print;
114    PrintModTime(Attrs);
115
116    for at in Attrs[1].keys():
117       if AttrInfo.has_key(at):
118          if AttrInfo[at][1] == 0:
119             print "      %-18s:" % (AttrInfo[at][0]),
120             for x in Attrs[1][at]:
121                print "'%s'" % (x),
122             print;
123          else:
124             OrderedIndex[AttrInfo[at][1]][1] = Attrs[1][at];
125
126    Keys = OrderedIndex.keys();
127    Keys.sort();
128    for at in Keys:
129       if at < 100 or RootMode != 0:
130          print " %3u) %-18s: " % (at,OrderedIndex[at][0]),
131          for x in OrderedIndex[at][1]:
132             print "'%s'" % (re.sub('[\n\r]','?',x)),
133          print;
134
135 def Overview(Attrs):
136    """Display a one-line overview for a given host"""
137    for i in ['host','architecture','distribution','access','status']:
138       if i not in Attrs[1].keys():
139          Attrs[1][i] = ['']
140    print "%-12s  %-10s  %-38s  %-25s %s" % (\
141       Attrs[1]['host'][0], \
142       Attrs[1]['architecture'][0], \
143       Attrs[1]['distribution'][0], \
144       Attrs[1]['access'][0], \
145       Attrs[1]['status'][0])
146
147 # Change a single attribute
148 def ChangeAttr(Attrs,Attr):
149    if (Attr in ["sponsor", "sshRSAHostKey", "purpose", "allowedGroups", "exportOptions", "ipHostNumber", "mXRecord", "sshdistAuthKeysHost"]):
150       return MultiChangeAttr(Attrs,Attr);
151
152    print "Old value: '%s'" % (GetAttr(Attrs,Attr,""));
153    print "Press enter to leave unchanged and a single space to set to empty";
154    NewValue = raw_input("New? ");
155
156    # Empty string
157    if (NewValue == ""):
158       print "Leaving unchanged.";
159       return;
160
161    # Single space designates delete, trap the delete error
162    if (NewValue == " "):
163       print "Deleting.",;
164       try:
165          l.modify_s(HostDn,[(ldap.MOD_DELETE,Attr,None)]);
166       except ldap.NO_SUCH_ATTRIBUTE:
167          pass;
168
169       print;
170       Attrs[1][Attr] = [""];
171       return;
172
173    # Set a new value
174    print "Setting.",;
175    l.modify_s(HostDn,[(ldap.MOD_REPLACE,Attr,NewValue)]);
176    Attrs[1][Attr] = [NewValue];
177    print;
178
179 def MultiChangeAttr(Attrs,Attr):
180    # Make sure that we have an entry
181    if not Attrs[1].has_key(Attr):
182       Attrs[1][Attr] = [];
183
184    Attrs[1][Attr].sort();
185    print "Old values: ",Attrs[1][Attr];
186
187    Mode = raw_input("[D]elete or [A]dd? ").upper()
188    if (Mode != 'D' and Mode != 'A'):
189       return;
190
191    NewValue = raw_input("Value? ");
192    # Empty string
193    if (NewValue == ""):
194       print "Leaving unchanged.";
195       return;
196
197    # Delete
198    if (Mode == "D"):
199       print "Deleting.",;
200       try:
201          l.modify_s(HostDn,[(ldap.MOD_DELETE,Attr,NewValue)]);
202       except ldap.NO_SUCH_ATTRIBUTE:
203          print "Failed";
204
205       print;
206       Attrs[1][Attr].remove(NewValue);
207       return;
208
209    # Set a new value
210    print "Setting.",;
211    l.modify_s(HostDn,[(ldap.MOD_ADD,Attr,NewValue)]);
212    Attrs[1][Attr].append(NewValue);
213    print;
214
215 def CalcTempFile():
216    unique = 0
217    while unique == 0:
218       name = mktemp()
219       try:
220          fd = os.open(name, O_CREAT | O_EXCL | O_WRONLY, 0600)
221       except OSError:
222          continue
223       os.close(fd)
224       unique = 1
225    return name
226
227
228 # Main program starts here
229 User = pwd.getpwuid(os.getuid())[0];
230 BindUser = User;
231 ListMode = 0
232 FingerPrints = 0
233 Host = None
234 # Process options
235 try:
236    (options, arguments) = getopt.getopt(sys.argv[1:], "nh:a:rlf")
237 except getopt.GetoptError, data:
238    print data
239    sys.exit(1)
240
241 for (switch, val) in options:
242    if (switch == '-h'):
243       Host = val;
244    elif (switch == '-a'):
245       BindUser = val;
246    elif (switch == '-r'):
247       RootMode = 1;
248    elif (switch == '-n'):
249       BindUser = "";
250    elif (switch == '-l'):
251       BindUser = "";
252       ListMode = 1
253    elif (switch == '-f'):
254       BindUser = "";
255       FingerPrints = 1
256
257 if (BindUser != ""):
258    l = passwdAccessLDAP(BaseDn, BindUser)
259 else:
260    l = connectLDAP()
261    l.simple_bind_s("","")
262
263 if ListMode == 1:
264    Attrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=*")
265    hosts = []
266    for hAttrs in Attrs:
267       hosts.append(hAttrs[1]['host'][0])
268    hosts.sort()
269
270    print "%-12s  %-10s  %-38s  %-25s %s" % ("Host name","Arch","Distribution","Access","Status")
271    print "-"*115
272    for host in hosts:
273       for hAttrs in Attrs:
274          if host == hAttrs[1]['host'][0]:
275             Overview(hAttrs)
276    sys.exit(0)
277 elif FingerPrints == 1:
278    if Host is not None:
279       Attrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=" + Host)
280    else:
281       Attrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=*")
282    hosts = []
283    for hAttrs in Attrs:
284       hosts.append(hAttrs[1]['host'][0])
285    hosts.sort()
286
287    tmpfile = CalcTempFile()
288    for host in hosts:
289       for hAttrs in Attrs:
290          if host == hAttrs[1]['host'][0]:
291             if 'sshRSAHostKey' in hAttrs[1].keys():
292                for key in hAttrs[1]['sshRSAHostKey']:
293                   tmp = open(tmpfile, 'w')
294                   tmp.write(key + '\n')
295                   tmp.close()
296                   fp = os.popen('/usr/bin/ssh-keygen -l -f ' + tmpfile, "r")
297                   input = fp.readline()
298                   fp.close()
299                   fingerprint = input.split(' ')
300                   print "%s %s root@%s" % (fingerprint[0], fingerprint[1], host)
301    os.unlink(tmpfile)
302    sys.exit(0)
303
304 HostDn = "host=" + Host + "," + HostBaseDn;
305
306 # Query the server for all of the attributes
307 Attrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=" + Host);
308 if len(Attrs) == 0:
309    print "Host",Host,"was not found.";
310    sys.exit(0);
311
312 # repeatedly show the account configuration
313 while(1):
314    ShowAttrs(Attrs[0]);
315    if (BindUser == ""):
316       sys.exit(0);
317
318    if RootMode == 1:
319       print "   a) Arbitary Change";
320    print "   n) New Host";
321    print "   d) Delete Host";
322    print "   u) Switch Hosts";
323    print "   x) Exit";
324
325    # Prompt
326    Response = raw_input("Change? ");
327    if (Response == "x" or Response == "X" or Response == "q" or
328        Response == "quit" or Response == "exit"):
329       break;
330
331    # Change who we are looking at
332    if (Response == 'u' or Response == 'U'):
333       NewHost = raw_input("Host? ");
334       if NewHost == "":
335          continue;
336       NAttrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=" + NewHost);
337       if len(NAttrs) == 0:
338          print "Host",NewHost,"was not found.";
339          continue;
340       Attrs = NAttrs;
341       Host = NewHost;
342       HostDn = "host=" + Host + "," + HostBaseDn;
343       OrderedIndex = copy.deepcopy(OrigOrderedIndex);
344       continue;
345
346    # Create a new entry and change to it Change who we are looking at
347    if (Response == 'n' or Response == 'N'):
348       NewHost = raw_input("Host? ");
349       if NewHost == "":
350          continue;
351       NAttrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=" + NewHost);
352       if len(NAttrs) != 0:
353          print "Host",NewHost,"already exists.";
354          continue;
355       NewHostName = raw_input("Hostname? ");
356       if NewHost == "":
357          continue;
358       Dn = "host=" + NewHost + "," + HostBaseDn;
359       l.add_s(Dn,[("host", NewHost),
360                   ("hostname", NewHostName),
361                   ("objectClass", ("top", "debianServer"))]);
362
363       # Switch
364       NAttrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=" + NewHost);
365       if len(NAttrs) == 0:
366          print "Host",NewHost,"was not found.";
367          continue;
368       Attrs = NAttrs;
369       Host = NewHost;
370       HostDn = "host=" + Host + "," + HostBaseDn;
371       OrderedIndex = copy.deepcopy(OrigOrderedIndex);
372       continue;
373
374    # Handle changing an arbitary value
375    if (Response == "a"):
376       Attr = raw_input("Attr? ");
377       ChangeAttr(Attrs[0],Attr);
378       continue;
379
380    if (Response == 'd'):
381       Really = raw_input("Really (type yes)? ");
382       if Really != 'yes':
383           continue;
384       print "Deleting",HostDn;
385       l.delete_s(HostDn);
386       continue;
387
388    # Convert the integer response
389    try:
390       ID = int(Response);
391       if (not OrderedIndex.has_key(ID) or (ID > 100 and RootMode == 0)):
392          raise ValueError;
393    except ValueError:
394       print "Invalid";
395       continue;
396
397    # Print the what to do prompt
398    print "Changing LDAP entry '%s' (%s)" % (OrderedIndex[ID][0],OrderedIndex[ID][2]);
399    print AttrPrompt[OrderedIndex[ID][2]][0];
400    ChangeAttr(Attrs[0],OrderedIndex[ID][2]);