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],};
58 AttrPrompt = {"description": ["Purpose of the machine"],
59 "hostname": ["The hostnames for the box (ipv4/ipv6)"],
60 "status": ["Blank if Up, explaination if not"],
61 "l": ["Physical location"],
62 "sponsor": ["Sponsors and their URLs"],
63 "distribution": ["The distribution version"],
64 "access": ["all, developer only, restricted"],
65 "admin": ["Admin email address"],
66 "architecture": ["Debian Architecture string"],
67 "machine": ["Hardware description"],
68 "memory": ["Installed RAM"],
69 "disk": ["Disk Space, RAID levels, etc"],
70 "physicalHost": ["The box hosting this virtual server"],
71 "sshRSAHostKey": ["A copy of /etc/ssh/ssh_*host_key.pub"],
72 "bandwidth": ["Available outbound"],
73 "purpose": ["The purposes of this host"],};
75 # Create a map of IDs to desc,value,attr
77 for at in AttrInfo.keys():
78 if (AttrInfo[at][1] != 0):
79 OrderedIndex[AttrInfo[at][1]] = [AttrInfo[at][0], "", at];
80 OrigOrderedIndex = copy.deepcopy(OrderedIndex);
82 # Print out the automatic time stamp information
83 def PrintModTime(Attrs):
84 Stamp = GetAttr(Attrs,"modifyTimestamp","");
86 Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
87 int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
88 print "%-24s:" % ("Record last modified on"), time.strftime("%a %d/%m/%Y %X UTC",Time),
89 print "by",ldap.explode_dn(GetAttr(Attrs,"modifiersName"),1)[0];
91 Stamp = GetAttr(Attrs,"createTimestamp","");
93 Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
94 int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
95 print "%-24s:" % ("Record created on"), time.strftime("%a %d/%m/%Y %X UTC",Time);
97 # Display all of the attributes in a numbered list
102 for at in Attrs[1].keys():
103 if AttrInfo.has_key(at):
104 if AttrInfo[at][1] == 0:
105 print " %-18s:" % (AttrInfo[at][0]),
106 for x in Attrs[1][at]:
110 OrderedIndex[AttrInfo[at][1]][1] = Attrs[1][at];
112 Keys = OrderedIndex.keys();
115 if at < 100 or RootMode != 0:
116 print " %3u) %-18s: " % (at,OrderedIndex[at][0]),
117 for x in OrderedIndex[at][1]:
118 print "'%s'" % (re.sub('[\n\r]','?',x)),
122 """Display a one-line overview for a given host"""
123 for i in ['host','architecture','distribution','access','status']:
124 if i not in Attrs[1].keys():
126 print "%-12s %-10s %-38s %-25s %s" % (\
127 Attrs[1]['host'][0], \
128 Attrs[1]['architecture'][0], \
129 Attrs[1]['distribution'][0], \
130 Attrs[1]['access'][0], \
131 Attrs[1]['status'][0])
133 # Change a single attribute
134 def ChangeAttr(Attrs,Attr):
135 if (Attr in ["sponsor", "sshRSAHostKey", "purpose"]):
136 return MultiChangeAttr(Attrs,Attr);
138 print "Old value: '%s'" % (GetAttr(Attrs,Attr,""));
139 print "Press enter to leave unchanged and a single space to set to empty";
140 NewValue = raw_input("New? ");
144 print "Leaving unchanged.";
147 # Single space designates delete, trap the delete error
148 if (NewValue == " "):
151 l.modify_s(HostDn,[(ldap.MOD_DELETE,Attr,None)]);
152 except ldap.NO_SUCH_ATTRIBUTE:
156 Attrs[1][Attr] = [""];
161 l.modify_s(HostDn,[(ldap.MOD_REPLACE,Attr,NewValue)]);
162 Attrs[1][Attr] = [NewValue];
165 def MultiChangeAttr(Attrs,Attr):
166 # Make sure that we have an entry
167 if not Attrs[1].has_key(Attr):
170 Attrs[1][Attr].sort();
171 print "Old values: ",Attrs[1][Attr];
173 Mode = raw_input("[D]elete or [A]dd? ").upper()
174 if (Mode != 'D' and Mode != 'A'):
177 NewValue = raw_input("Value? ");
180 print "Leaving unchanged.";
187 l.modify_s(HostDn,[(ldap.MOD_DELETE,Attr,NewValue)]);
188 except ldap.NO_SUCH_ATTRIBUTE:
192 Attrs[1][Attr].remove(NewValue);
197 l.modify_s(HostDn,[(ldap.MOD_ADD,Attr,NewValue)]);
198 Attrs[1][Attr].append(NewValue);
206 fd = os.open(name, O_CREAT | O_EXCL | O_WRONLY, 0600)
214 # Main program starts here
215 User = pwd.getpwuid(os.getuid())[0];
222 (options, arguments) = getopt.getopt(sys.argv[1:], "nh:a:rlf")
223 except getopt.GetoptError, data:
227 for (switch, val) in options:
230 elif (switch == '-a'):
232 elif (switch == '-r'):
234 elif (switch == '-n'):
236 elif (switch == '-l'):
239 elif (switch == '-f'):
244 l = passwdAccessLDAP(LDAPServer, BaseDn, BindUser)
246 l = ldap.open(LDAPServer);
247 l.simple_bind_s("","")
250 Attrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=*")
253 hosts.append(hAttrs[1]['host'][0])
256 print "%-12s %-10s %-38s %-25s %s" % ("Host name","Arch","Distribution","Access","Status")
260 if host == hAttrs[1]['host'][0]:
263 elif FingerPrints == 1:
265 Attrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=" + Host)
267 Attrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=*")
270 hosts.append(hAttrs[1]['host'][0])
273 tmpfile = CalcTempFile()
276 if host == hAttrs[1]['host'][0]:
277 if 'sshRSAHostKey' in hAttrs[1].keys():
278 for key in hAttrs[1]['sshRSAHostKey']:
279 tmp = open(tmpfile, 'w')
280 tmp.write(key + '\n')
282 fp = os.popen('/usr/bin/ssh-keygen -l -f ' + tmpfile, "r")
283 input = fp.readline()
285 fingerprint = input.split(' ')
286 print "%s %s root@%s" % (fingerprint[0], fingerprint[1], host)
290 HostDn = "host=" + Host + "," + HostBaseDn;
292 # Query the server for all of the attributes
293 Attrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=" + Host);
295 print "Host",Host,"was not found.";
298 # repeatedly show the account configuration
305 print " a) Arbitary Change";
306 print " n) New Host";
307 print " d) Delete Host";
308 print " u) Switch Hosts";
312 Response = raw_input("Change? ");
313 if (Response == "x" or Response == "X" or Response == "q" or
314 Response == "quit" or Response == "exit"):
317 # Change who we are looking at
318 if (Response == 'u' or Response == 'U'):
319 NewHost = raw_input("Host? ");
322 NAttrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=" + NewHost);
324 print "Host",NewHost,"was not found.";
328 HostDn = "host=" + Host + "," + HostBaseDn;
329 OrderedIndex = copy.deepcopy(OrigOrderedIndex);
332 # Create a new entry and change to it Change who we are looking at
333 if (Response == 'n' or Response == 'N'):
334 NewHost = raw_input("Host? ");
337 NAttrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=" + NewHost);
339 print "Host",NewHost,"already exists.";
341 NewHostName = raw_input("Hostname? ");
344 Dn = "host=" + NewHost + "," + HostBaseDn;
345 l.add_s(Dn,[("host", NewHost),
346 ("hostname", NewHostName),
347 ("objectClass", ("top", "debianServer"))]);
350 NAttrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=" + NewHost);
352 print "Host",NewHost,"was not found.";
356 HostDn = "host=" + Host + "," + HostBaseDn;
357 OrderedIndex = copy.deepcopy(OrigOrderedIndex);
360 # Handle changing an arbitary value
361 if (Response == "a"):
362 Attr = raw_input("Attr? ");
363 ChangeAttr(Attrs[0],Attr);
366 if (Response == 'd'):
367 Really = raw_input("Really (type yes)? ");
370 print "Deleting",HostDn;
374 # Convert the integer response
377 if (not OrderedIndex.has_key(ID) or (ID > 100 and RootMode == 0)):
383 # Print the what to do prompt
384 print "Changing LDAP entry '%s' (%s)" % (OrderedIndex[ID][0],OrderedIndex[ID][2]);
385 print AttrPrompt[OrderedIndex[ID][2]][0];
386 ChangeAttr(Attrs[0],OrderedIndex[ID][2]);