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>
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.
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.
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.
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.
28 # Usage: userinfo -a <user> -u <user> -c <user> -r
29 # -a Set the authentication user (the user whose password you are
31 # -h Set the host to display
32 # -l list all hosts and their status
33 # -f list all SSH fingerprints
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 *;
41 AttrInfo = {"description": ["Machine Descr.", 1],
42 "hostname": ["Host names", 2],
43 "status": ["Status", 3],
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],
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],
61 AttrPrompt = {"description": ["Purpose of the machine"],
62 "hostname": ["The hostnames for the box (ipv4/ipv6)"],
63 "status": ["Blank if Up, explaination if not"],
64 "l": ["Physical location"],
65 "sponsor": ["Sponsors and their URLs"],
66 "distribution": ["The distribution version"],
67 "access": ["all, developer only, restricted"],
68 "admin": ["Admin email address"],
69 "architecture": ["Debian Architecture string"],
70 "machine": ["Hardware description"],
71 "memory": ["Installed RAM"],
72 "disk": ["Disk Space, RAID levels, etc"],
73 "physicalHost": ["The box hosting this virtual server"],
74 "sshRSAHostKey": ["A copy of /etc/ssh/ssh_*host_key.pub"],
75 "bandwidth": ["Available outbound"],
76 "purpose": ["The purposes of this host"],
77 "allowedGroups": ["allowed Groups on this host"],
78 "exportOptions": ["additional export options"],
81 # Create a map of IDs to desc,value,attr
83 for at in AttrInfo.keys():
84 if (AttrInfo[at][1] != 0):
85 OrderedIndex[AttrInfo[at][1]] = [AttrInfo[at][0], "", at];
86 OrigOrderedIndex = copy.deepcopy(OrderedIndex);
88 # Print out the automatic time stamp information
89 def PrintModTime(Attrs):
90 Stamp = GetAttr(Attrs,"modifyTimestamp","");
92 Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
93 int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
94 print "%-24s:" % ("Record last modified on"), time.strftime("%a %d/%m/%Y %X UTC",Time),
95 print "by",ldap.explode_dn(GetAttr(Attrs,"modifiersName"),1)[0];
97 Stamp = GetAttr(Attrs,"createTimestamp","");
99 Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
100 int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
101 print "%-24s:" % ("Record created on"), time.strftime("%a %d/%m/%Y %X UTC",Time);
103 # Display all of the attributes in a numbered list
104 def ShowAttrs(Attrs):
108 for at in Attrs[1].keys():
109 if AttrInfo.has_key(at):
110 if AttrInfo[at][1] == 0:
111 print " %-18s:" % (AttrInfo[at][0]),
112 for x in Attrs[1][at]:
116 OrderedIndex[AttrInfo[at][1]][1] = Attrs[1][at];
118 Keys = OrderedIndex.keys();
121 if at < 100 or RootMode != 0:
122 print " %3u) %-18s: " % (at,OrderedIndex[at][0]),
123 for x in OrderedIndex[at][1]:
124 print "'%s'" % (re.sub('[\n\r]','?',x)),
128 """Display a one-line overview for a given host"""
129 for i in ['host','architecture','distribution','access','status']:
130 if i not in Attrs[1].keys():
132 print "%-12s %-10s %-38s %-25s %s" % (\
133 Attrs[1]['host'][0], \
134 Attrs[1]['architecture'][0], \
135 Attrs[1]['distribution'][0], \
136 Attrs[1]['access'][0], \
137 Attrs[1]['status'][0])
139 # Change a single attribute
140 def ChangeAttr(Attrs,Attr):
141 if (Attr in ["sponsor", "sshRSAHostKey", "purpose", "allowedGroups", "exportOptions"]):
142 return MultiChangeAttr(Attrs,Attr);
144 print "Old value: '%s'" % (GetAttr(Attrs,Attr,""));
145 print "Press enter to leave unchanged and a single space to set to empty";
146 NewValue = raw_input("New? ");
150 print "Leaving unchanged.";
153 # Single space designates delete, trap the delete error
154 if (NewValue == " "):
157 l.modify_s(HostDn,[(ldap.MOD_DELETE,Attr,None)]);
158 except ldap.NO_SUCH_ATTRIBUTE:
162 Attrs[1][Attr] = [""];
167 l.modify_s(HostDn,[(ldap.MOD_REPLACE,Attr,NewValue)]);
168 Attrs[1][Attr] = [NewValue];
171 def MultiChangeAttr(Attrs,Attr):
172 # Make sure that we have an entry
173 if not Attrs[1].has_key(Attr):
176 Attrs[1][Attr].sort();
177 print "Old values: ",Attrs[1][Attr];
179 Mode = raw_input("[D]elete or [A]dd? ").upper()
180 if (Mode != 'D' and Mode != 'A'):
183 NewValue = raw_input("Value? ");
186 print "Leaving unchanged.";
193 l.modify_s(HostDn,[(ldap.MOD_DELETE,Attr,NewValue)]);
194 except ldap.NO_SUCH_ATTRIBUTE:
198 Attrs[1][Attr].remove(NewValue);
203 l.modify_s(HostDn,[(ldap.MOD_ADD,Attr,NewValue)]);
204 Attrs[1][Attr].append(NewValue);
212 fd = os.open(name, O_CREAT | O_EXCL | O_WRONLY, 0600)
220 # Main program starts here
221 User = pwd.getpwuid(os.getuid())[0];
228 (options, arguments) = getopt.getopt(sys.argv[1:], "nh:a:rlf")
229 except getopt.GetoptError, data:
233 for (switch, val) in options:
236 elif (switch == '-a'):
238 elif (switch == '-r'):
240 elif (switch == '-n'):
242 elif (switch == '-l'):
245 elif (switch == '-f'):
250 l = passwdAccessLDAP(BaseDn, BindUser)
253 l.simple_bind_s("","")
256 Attrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=*")
259 hosts.append(hAttrs[1]['host'][0])
262 print "%-12s %-10s %-38s %-25s %s" % ("Host name","Arch","Distribution","Access","Status")
266 if host == hAttrs[1]['host'][0]:
269 elif FingerPrints == 1:
271 Attrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=" + Host)
273 Attrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=*")
276 hosts.append(hAttrs[1]['host'][0])
279 tmpfile = CalcTempFile()
282 if host == hAttrs[1]['host'][0]:
283 if 'sshRSAHostKey' in hAttrs[1].keys():
284 for key in hAttrs[1]['sshRSAHostKey']:
285 tmp = open(tmpfile, 'w')
286 tmp.write(key + '\n')
288 fp = os.popen('/usr/bin/ssh-keygen -l -f ' + tmpfile, "r")
289 input = fp.readline()
291 fingerprint = input.split(' ')
292 print "%s %s root@%s" % (fingerprint[0], fingerprint[1], host)
296 HostDn = "host=" + Host + "," + HostBaseDn;
298 # Query the server for all of the attributes
299 Attrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=" + Host);
301 print "Host",Host,"was not found.";
304 # repeatedly show the account configuration
311 print " a) Arbitary Change";
312 print " n) New Host";
313 print " d) Delete Host";
314 print " u) Switch Hosts";
318 Response = raw_input("Change? ");
319 if (Response == "x" or Response == "X" or Response == "q" or
320 Response == "quit" or Response == "exit"):
323 # Change who we are looking at
324 if (Response == 'u' or Response == 'U'):
325 NewHost = raw_input("Host? ");
328 NAttrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=" + NewHost);
330 print "Host",NewHost,"was not found.";
334 HostDn = "host=" + Host + "," + HostBaseDn;
335 OrderedIndex = copy.deepcopy(OrigOrderedIndex);
338 # Create a new entry and change to it Change who we are looking at
339 if (Response == 'n' or Response == 'N'):
340 NewHost = raw_input("Host? ");
343 NAttrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=" + NewHost);
345 print "Host",NewHost,"already exists.";
347 NewHostName = raw_input("Hostname? ");
350 Dn = "host=" + NewHost + "," + HostBaseDn;
351 l.add_s(Dn,[("host", NewHost),
352 ("hostname", NewHostName),
353 ("objectClass", ("top", "debianServer"))]);
356 NAttrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=" + NewHost);
358 print "Host",NewHost,"was not found.";
362 HostDn = "host=" + Host + "," + HostBaseDn;
363 OrderedIndex = copy.deepcopy(OrigOrderedIndex);
366 # Handle changing an arbitary value
367 if (Response == "a"):
368 Attr = raw_input("Attr? ");
369 ChangeAttr(Attrs[0],Attr);
372 if (Response == 'd'):
373 Really = raw_input("Really (type yes)? ");
376 print "Deleting",HostDn;
380 # Convert the integer response
383 if (not OrderedIndex.has_key(ID) or (ID > 100 and RootMode == 0)):
389 # Print the what to do prompt
390 print "Changing LDAP entry '%s' (%s)" % (OrderedIndex[ID][0],OrderedIndex[ID][2]);
391 print AttrPrompt[OrderedIndex[ID][2]][0];
392 ChangeAttr(Attrs[0],OrderedIndex[ID][2]);