userdir-ldap (0.3.15+xxx) XXunstable; urgency=low
+ [ Peter Palfrader ]
* Ship userdir-ldap.schema with the package, add a note that it is
now version-controlled in bzr on top of the file.
* Get rid of debian/conffiles, wich only listed files in /etc anyway.
* ud-roleadd: Do not try to make role accounts of objectClass
inetOrgPerson, that doesn't work.
- -- Peter Palfrader <weasel@debian.org> Tue, 25 Dec 2007 13:08:50 +0100
+ [ Mark Hymers ]
+ * ud-userimport, ud-groupadd, ud-roleadd, ud-useradd, userdir_ldap.py:
+ Update ud-userimport to use the same objectClasses as
+ ud-{user,group,role}add and abstract them out into userdir_ldap.py
+ * ud-useradd: Avoid a TypeError exception when constructing the template
+ filename
+ * Remove use of deprecated functions from the string module
+ * ud-arbimport: os.exit -> sys.exit
+
+ -- Mark Hymers <mhy@debian.org> Wed, 26 Dec 2007 20:54:28 +0000
userdir-ldap (0.3.15) unstable; urgency=low
by addr=127.0.0.1 read
by domain=.*\.debian\.org read
by * none
-access to attrs=c,l,loginShell,ircNick,labeledURL
+access to attrs=c,l,loginShell,ircNick
by dn="uid=admin,ou=users,dc=debian,dc=org" write
by group="uid=admin,ou=users,dc=debian,dc=org" write
by self write
# End----------
+Note that in more modern versions of slapd, the "by addr" and "by domain"
+syntax has changed and the following should be used instead:
+ by peername.ip=127.0.0.1 read
+ by domain.subtree=debian.org read
+
+
+
Here is the initial seed file to import and setup the proper entries:
dn: dc=org
# -e /etc/userdir-ldap/templtes/error-reply -- test.sh
import sys, traceback, time, os;
-import string, pwd, getopt;
+import pwd, getopt;
from userdir_gpg import *;
EX_TEMPFAIL = 75;
elif (switch == '-e'):
ErrorTemplate = val;
elif (switch == '-k'):
- SetKeyrings(string.split(val,":"));
+ SetKeyrings(val.split(":"));
elif (switch == '-a'):
ReplyTo = val;
elif (switch == '-d'):
Msg = GetClearSig(Email);
ErrMsg = "Message is not PGP signed:"
- if string.find(Msg[0],"-----BEGIN PGP SIGNED MESSAGE-----") == -1:
+ if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1:
raise Error, "No PGP signature";
# Check the signature
ErrMsg = "Problem stripping MIME headers from the decoded message"
if Msg[1] == 1:
try:
- Index = string.index(Res[3],"\n\n") + 2;
+ Index = Res[3].index("\n\n") + 2;
except ValueError:
- Index = string.index(Res[3],"\n\r\n") + 3;
+ Index = Res[3].index("\n\r\n") + 3;
PlainText = Res[3][Index:];
else:
PlainText = Res[3];
os.environ["REPLYTO"] = Sender;
# Invoke the child
- Child = os.popen(string.join(arguments," "),"w");
+ Child = os.popen(" ".join(arguments),"w");
Child.write(PlainText);
if Child.close() != None:
raise Error, "Child gave a non-zero return code";
# -e /etc/userdir-ldap/templtes/error-reply -- test.sh
import sys, traceback, time, os;
-import string, pwd, getopt;
+import pwd, getopt;
from userdir_gpg import *;
EX_TEMPFAIL = 75;
if (switch == '-r'):
ReplayCacheFile = val;
elif (switch == '-k'):
- SetKeyrings(string.split(val,":"));
+ SetKeyrings(val.split(":"));
elif (switch == '-d'):
LDAPDn = val;
elif (switch == '-l'):
raise Error, "PGP/MIME disallowed";
ErrMsg = "Message is not PGP signed:"
- if string.find(Msg[0],"-----BEGIN PGP SIGNED MESSAGE-----") == -1:
+ if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1:
raise Error, "No PGP signature";
# Check the signature
while 1:
Line = F.readline();
if Line == "": break;
- if string.find(Res[3],string.strip(Line)) == -1:
- raise Error,"Phrase '%s' was not found"%(string.strip(Line));
+ if Res[3].find(Line.strip()) == -1:
+ raise Error,"Phrase '%s' was not found" % (Line.strip())
except:
ErrMsg = "[%s] \"%s\" \"%s %s\"\n"%(Now,MsgID,ErrMsg,sys.exc_value);
# the form of:
# uid: <data>
-import string, re, time, ldap, getopt, sys;
+import re, time, ldap, getopt, sys;
from userdir_ldap import *;
# Process options
NoAct = 1;
if len(arguments) == 0:
print "Give the key to assignt to then the file to import";
- os.exit(0);
+ sys.exit(0)
# Main program starts here
l = passwdAccessLDAP(LDAPServer, BaseDn, AdminUser)
if User == None:
User = Split[0];
if Split[0] == User:
- Set.append(string.strip(Split[1]));
+ Set.append(Split[1].strip());
continue;
else:
if len(Set) == 0:
if Line == "":
break;
User = Split[0];
- Set = [string.strip(Split[1])];
+ Set = [Split[1].strip()];
#!/usr/bin/env python
# -*- mode: python -*-
import userdir_gpg, userdir_ldap, sys, traceback, time, ldap, os, getopt;
-import string, pwd
+import pwd
from userdir_gpg import *;
from userdir_ldap import *;
ErrLog.write(S);
return None;
- if string.find(Msg[0],"-----BEGIN PGP SIGNED MESSAGE-----") == -1:
+ if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1:
return None;
Res = GPGCheckSig(Msg[0]);
l = ldap.open(LDAPServer);
if Debug == None:
F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
- AccessPass = string.split(string.strip(F.readline())," ");
+ AccessPass = F.readline().strip().split(" ")
l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
F.close();
else:
# This script tries to match a list of email addresses to the ldap database
# uids. It makes use of the PGP key ring to determine matches
-import string, re, time, ldap, getopt, sys;
+import re, time, ldap, getopt, sys;
from userdir_ldap import *;
from userdir_gpg import *;
def ImportForward(File,EmailMap):
F = open(File,"r");
while(1):
- Line = string.strip(F.readline());
+ Line = F.readline().strip()
if Line == "":
break;
- Split = string.split(Line,":");
+ Split = Line.split(":")
if len(Split) != 2:
continue;
- Addr = string.strip(Split[1]);
+ Addr = Split[1].strip()
if EmailMap.has_key(Addr) and EmailMap[Addr] != Split[0]:
print "Dup Over Emap",Line,Split
else:
Line = F.readline();
if Line == "":
break;
- Line = string.strip(Line);
+ Line = Line.strip()
- Split = string.split(Line,":");
+ Split = Line.split(":")
if len(Split) != 2:
continue;
- OverMap[Split[0]] = string.strip(Split[1]);
+ OverMap[Split[0]] = Split[1].strip()
F.close();
(options, arguments) = getopt.getopt(sys.argv[1:], "o:f:")
Args.append("--keyring");
Args.append(x);
Args = Args + GPGSearchOptions + [" 2> /dev/null"]
-Keys = os.popen(string.join(Args," "),"r");
+Keys = os.popen(" ".join(Args),"r")
l = ldap.open(LDAPServer);
l.simple_bind_s("","");
if Line == "":
break;
- Split = string.split(Line,":");
+ Split = Line.split(":")
if len(Split) >= 8 and Split[0] == "pub":
if FingerPrint != None and UID != None:
for x in Emails:
Line = sys.stdin.readline();
if Line == "":
break;
- Line = string.strip(Line);
+ Line = Line.strip()
- Split = string.split(Line,"@");
+ Split = Line.split("@")
if len(Split) != 2:
continue;
if Split[1] == EmailAppend:
if FinalMap.has_key(Line):
print "Dup",Line
- Split2 = string.split(Split[0],"-");
+ Split2 = Split[0].split("-")
FinalMap[Line] = Split2[0];
continue;
continue;
# Try again splitting off common address appendage modes
- Split2 = string.split(Split[0],"-");
+ Split2 = Split[0].split("-")
Addr = Split2[0]+'@'+Split[1];
if EmailMap.has_key(Addr):
if FinalMap.has_key(Addr):
#
# It also understand .qmail type files
-import string, re, time, getopt, os, sys, pwd, stat;
+import re, time, getopt, os, sys, pwd, stat;
AddressSplit = re.compile("<(.*)>");
while (1):
- File = string.strip(sys.stdin.readline());
+ File = sys.stdin.readline().strip()
if File == "":
break;
Forward = open(File,"r");
Line = None;
while (1):
- Line2 = string.strip(Forward.readline());
+ Line2 = Forward.readline().strip()
if Line2 == "":
break;
if Line2[0] == '#' or Line2[0] == '\n':
# Abort for funky things like pipes or directions to mailboxes
if Line[0] == '/' or Line[0] == '|' or Line[0] == '.' or Line[-1] == '/' or \
- string.find(Line,'@') == -1:
+ Line.find('@') == -1:
print "Invalid2", File;
continue;
DNSZone = ".debian.net"
def Sanitize(Str):
- return string.translate(Str,string.maketrans("\n\r\t","$$$"));
+ return Str.translate(string.maketrans("\n\r\t","$$$"))
def DoLink(From,To,File):
try: posix.remove(To+File);
# If the account is locked, mark it as such in shadow
# See Debian Bug #308229 for why we set it to 1 instead of 0
- if (string.find(GetAttr(x,"userPassword"),"*LK*") != -1) \
+ if (GetAttr(x,"userPassword").find("*LK*") != -1) \
or GetAttr(x,"userPassword").startswith("!"):
ShadowExpire = '1'
else:
# If the account is locked, do not write it.
# This is a partial stop-gap. The ssh also needs to change this
# to ignore ~/.ssh/authorized* files.
- if (string.find(GetAttr(x,"userPassword"),"*LK*") != -1) \
+ if (GetAttr(x,"userPassword").find("*LK*") != -1) \
or GetAttr(x,"userPassword").startswith("!"):
continue;
continue;
# If the account is locked, do not write it
- if (string.find(GetAttr(x,"userPassword"),"*LK*") != -1) \
+ if (GetAttr(x,"userPassword").find("*LK*") != -1) \
or GetAttr(x,"userPassword").startswith("!"):
continue;
Line = ""
# *LK* is the reference value for a locked account
# password starting with ! is also a locked account
- if string.find(Pass,"*LK*") != -1 or Pass.startswith("!"):
+ if Pass.find("*LK*") != -1 or Pass.startswith("!"):
# Format is <login>:<reason>
Line = "%s:%s" % (GetAttr(x,"uid"), "Account is locked")
Reason = None
# If the account is locked, disable incoming mail
- if (string.find(GetAttr(x,"userPassword"),"*LK*") != -1):
+ if (GetAttr(x,"userPassword").find("*LK*") != -1):
if GetAttr(x,"uid") == "luther":
continue
else:
try:
F.write("; %s\n"%(EmailAddress(x)));
for z in x[1]["dnsZoneEntry"]:
- Split = string.split(string.lower(z));
- if string.lower(Split[1]) == 'in':
+ Split = z.lower().split()
+ if Split[1].lower() == 'in':
for y in range(0,len(Split)):
if Split[y] == "$":
Split[y] = "\n\t";
- Line = string.join(Split," ") + "\n";
+ Line = " ".join(Split) + "\n";
F.write(Line);
Host = Split[0] + DNSZone;
F.write("; Has BSMTP\n");
# Write some identification information
- if string.lower(Split[2]) == "a":
+ if Split[2].lower() == "a":
Line = "%s IN TXT \"%s\"\n"%(Split[0],EmailAddress(x));
for y in x[1]["keyFingerPrint"]:
Line = Line + "%s IN TXT \"PGP %s\"\n"%(Split[0],FormatPGPKey(y));
Host = GetAttr(x,"hostname");
Algorithm = None
for I in x[1]["sshRSAHostKey"]:
- Split = string.split(I)
+ Split = I.split()
if Split[0] == 'ssh-rsa':
Algorithm = 1
if Split[0] == 'ssh-dss':
continue;
try:
for z in x[1]["dnsZoneEntry"]:
- Split = string.split(string.lower(z));
- if string.lower(Split[1]) == 'in':
+ Split = z.lower().split()
+ if Split[1].lower() == 'in':
for y in range(0,len(Split)):
if Split[y] == "$":
Split[y] = "\n\t";
- Line = string.join(Split," ") + "\n";
+ Line = " ".join(Split) + "\n";
Host = Split[0] + DNSZone;
if BSMTPCheck.match(Line) != None:
x[1].has_key("sshRSAHostKey") == 0:
continue;
Host = GetAttr(x,"hostname");
- SHost = string.find(Host,".");
+ SHost = Host.find(".")
for I in x[1]["sshRSAHostKey"]:
if SHost == None:
Line = "%s,%s %s" %(Host,socket.gethostbyname(Host),I);
# Connect to the ldap server
l = ldap.open(LDAPServer);
F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
-Pass = string.split(string.strip(F.readline())," ");
+Pass = F.readline().strip().split(" ")
F.close();
l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1]);
Line = F.readline();
if Line == "":
break;
- Line = string.strip(Line);
+ Line = Line.strip()
if Line == "":
continue;
if Line[0] == '#':
continue;
- Split = string.split(Line," ");
+ Split = Line.split(" ")
OutDir = GenerateDir + '/' + Split[0] + '/';
try: os.mkdir(OutDir);
except: pass;
# in the directory but not in the key ring will be removed from the
# directory.
-import string, re, time, ldap, getopt, sys, pwd, os;
+import re, time, ldap, getopt, sys, pwd, os;
from userdir_ldap import *;
from userdir_gpg import *;
if Line == "":
break;
Split = re.split("[:\n]",Line);
- UnknownMap[Split[0]] = string.strip(Split[1]);
+ UnknownMap[Split[0]] = Split[1].strip()
# Process options
AdminUser = pwd.getpwuid(os.getuid())[0];
Args = [GPGPath] + GPGBasicOptions;
for x in arguments:
Args.append("--keyring");
- if string.find(x,"/") == -1:
+ if x.find("/") == -1:
Args.append("./"+x);
else:
Args.append(x);
Args = Args + GPGSearchOptions + [" 2> /dev/null"]
-Keys = os.popen(string.join(Args," "),"r");
+Keys = os.popen(" ".join(Args),"r");
# Loop over the GPG key file
Outstanding = 0;
if Line == "":
break;
- Split = string.split(Line,":");
+ Split = Line.split(":")
if len(Split) < 8 or Split[0] != "pub":
continue;
Line2 = Keys.readline();
if Line2 == "":
break;
- Split2 = string.split(Line2,":");
+ Split2 = Line2.split(":");
if len(Split2) < 11 or Split2[0] != "fpr":
continue;
break;
#!/usr/bin/env python
# -*- mode: python -*-
-import string, re, time, ldap, getopt, sys, pwd, os;
+import re, time, ldap, getopt, sys, pwd, os;
from userdir_gpg import *;
Output = "extrakeys.gpg";
Args = [GPGPath] + GPGBasicOptions;
for x in arguments:
Args.append("--keyring");
- if string.find(x,"/") == -1:
+ if x.find("/") == -1:
Args.append("./"+x);
else:
Args.append(x);
Args.append("--fast-list-mode");
Args.append("--list-sigs");
Args = Args + GPGSearchOptions + [" 2> /dev/null"]
-Keys = os.popen(string.join(Args," "),"r");
+Keys = os.popen(" ".join(Args),"r");
# Loop over the GPG key file
HaveKeys = {};
if Line == "":
break;
- Split = string.split(Line,":");
+ Split = Line.split(":");
if len(Split) >= 8 and Split[0] == "pub":
HaveKeys[Split[4]] = "";
continue;
Args = [GPGPath] + GPGBasicOptions;
for x in [Output]:
Args.append("--keyring");
- if string.find(x,"/") == -1:
+ if x.find("/") == -1:
Args.append("./"+x);
else:
Args.append(x);
OldArgs = Args;
Args = Args + GPGSearchOptions + [" 2> /dev/null"]
-Keys = os.popen(string.join(Args," "),"r");
+Keys = os.popen(" ".join(Args),"r");
print "Reading keys from output ring";
while(1):
if Line == "":
break;
- Split = string.split(Line,":");
+ Split = Line.split(":");
if len(Split) >= 8 and Split[0] == "pub":
HaveKeys[Split[4]] = "";
continue;
OldI = I;
I = I - 20;
if I < 0: I = 0;
- print string.join(Args+KeysToFetch[I:OldI]," ")
- Fetcher = os.popen(string.join(Args+KeysToFetch[I:OldI]," "),"r");
+ print " ".join(Args+KeysToFetch[I:OldI])
+ Fetcher = os.popen(" ".join(Args+KeysToFetch[I:OldI]),"r");
while(1):
Line = Fetcher.readline();
if Line == "":
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-import string, re, time, ldap, getopt, sys, os, pwd;
+import re, time, ldap, getopt, sys, os, pwd;
from userdir_ldap import *;
from userdir_gpg import *;
sys.stdout.flush();
l.add_s(Dn,[("gid",Group),
("gidNumber",str(Id)),
- ("objectClass",("top", "debianGroup"))]);
+ ("objectClass", GroupObjectClasses)])
# Checks a directory against the passwd file assuming it is the home
# directory directory
-import string, ldap, getopt, sys, os, pwd;
+import ldap, getopt, sys, os, pwd;
for x in os.listdir(sys.argv[1]):
try:
# -l list all hosts and their status
# -f list all SSH fingerprints
-import string, time, os, pwd, sys, getopt, ldap, crypt, readline, copy;
+import time, os, pwd, sys, getopt, ldap, crypt, readline, copy;
from tempfile import mktemp
from os import O_CREAT, O_EXCL, O_WRONLY
from userdir_ldap import *;
Attrs[1][Attr].sort();
print "Old values: ",Attrs[1][Attr];
- Mode = string.upper(raw_input("[D]elete or [A]dd? "));
+ Mode = raw_input("[D]elete or [A]dd? ").upper()
if (Mode != 'D' and Mode != 'A'):
return;
# -r Enable 'root' functions, do this if your uid has access to
# restricted variables.
-import string, time, os, pwd, sys, getopt, ldap, crypt, readline, copy;
+import time, os, pwd, sys, getopt, ldap, crypt, readline, copy;
from userdir_ldap import *;
RootMode = 0;
Attrs[1][Attr].sort();
print "Old values: ",Attrs[1][Attr];
- Mode = string.upper(raw_input("[D]elete or [A]dd? "));
+ Mode = raw_input("[D]elete or [A]dd? ").upper()
if (Mode != 'D' and Mode != 'A'):
return;
# Call with nokey to generate a missing key report
# Call with noforward to generate a missing .forward report
-import string, re, time, ldap, getopt, sys;
+import re, time, ldap, getopt, sys;
from userdir_ldap import *;
def ShowDups(Attrs,Len):
#!/usr/bin/env python
# -*- mode: python -*-
import userdir_gpg, userdir_ldap, sys, traceback, time, ldap, os;
-import string, pwd
+import pwd
from userdir_gpg import *;
from userdir_ldap import *;
# Handle a position change message, the line format is:
# Lat: -12412.23 Long: +12341.2342
def DoPosition(Str,Attrs):
- Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$",string.lower(Str));
+ Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$", Str.lower())
if Match == None:
return None;
# Handle an RBL list (mailRBL, mailRHSBL, mailWhitelist)
def DoRBL(Str,Attrs):
- Match = re.compile('^mail(rbl|rhsbl|whitelist) ([-a-z0-9.]+)$').match(string.lower(Str))
+ Match = re.compile('^mail(rbl|rhsbl|whitelist) ([-a-z0-9.]+)$').match(Str.lower())
if Match == None:
return None
Attrs = [];
Show = 0;
for Line in Lines:
- Line = string.strip(Line);
+ Line = Line.strip()
if Line == "":
continue;
# Connect to the ldap server
l = ldap.open(LDAPServer);
F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
- AccessPass = string.split(string.strip(F.readline())," ");
+ AccessPass = F.readline().strip().split(" ")
F.close();
# Modify the record
l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
oldAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
- if ((string.find(GetAttr(oldAttrs[0],"userPassword"),"*LK*") != -1)
+ if ((GetAttr(oldAttrs[0],"userPassword").find("*LK*") != -1)
or GetAttr(oldAttrs[0],"userPassword").startswith("!")):
raise Error, "This account is locked";
Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
# Connect to the ldap server
l = ldap.open(LDAPServer);
F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
- AccessPass = string.split(string.strip(F.readline())," ");
+ AccessPass = F.readline().strip().split(" ")
F.close();
l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
# Check for a locked account
Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
- if (string.find(GetAttr(Attrs[0],"userPassword"),"*LK*") != -1) \
+ if (GetAttr(Attrs[0],"userPassword").find("*LK*") != -1) \
or GetAttr(Attrs[0],"userPassword").startswith("!"):
raise Error, "This account is locked";
Msg = GetClearSig(Email);
ErrMsg = "Message is not PGP signed:"
- if string.find(Msg[0],"-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
- string.find(Msg[0],"-----BEGIN PGP MESSAGE-----") == -1:
+ if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
+ Msg[0].find("-----BEGIN PGP MESSAGE-----") == -1:
raise Error, "No PGP signature";
# Check the signature
ErrMsg = "Problem stripping MIME headers from the decoded message"
if Msg[1] == 1:
try:
- Index = string.index(Res[3],"\n\n") + 2;
+ Index = Res[3].index("\n\n") + 2;
except ValueError:
- Index = string.index(Res[3],"\n\r\n") + 3;
+ Index = Res[3].index("\n\r\n") + 3;
PlainText = Res[3][Index:];
else:
PlainText = Res[3];
if sys.argv[1] == "ping":
Reply = HandlePing(Reply,Attrs[0],Res[2]);
elif sys.argv[1] == "chpass":
- if string.find(string.strip(PlainText),"Please change my Debian password") != 0:
+ if PlainText.strip().find("Please change my Debian password") != 0:
raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
Reply = HandleChPass(Reply,Attrs[0],Res[2]);
elif sys.argv[1] == "change":
# -*- mode: python -*-
# Checks the passwd file to make sure all entries are in the directory
-import string, ldap, getopt, sys, os;
+import ldap, getopt, sys, os;
from userdir_ldap import *;
def PassCheck(l,File,HomePrefix):
if Line == "":
break;
- Split = string.split(Line,":");
+ Split = Line.split(":")
if UIDMap.has_key(Split[0]) == 0:
print Line,
continue;
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-import string, time, ldap, getopt, sys, os, pwd
+import time, ldap, getopt, sys, os, pwd
from userdir_ldap import *
# This tries to search for a free UID. There are two possible ways to do
sys.stdout.flush()
Details = [("uid",account),
- ("objectClass",
- ("top","debianAccount","shadowAccount","debianRoleAccount")),
+ ("objectClass", RoleObjectClasses),
("uidNumber",str(uidNumber)),
("gidNumber",str(gidNumber)),
("gecos",cn+",,,,"),
#
# It also understand .qmail type files
-import string, re, time, getopt, os, sys, pwd, stat;
+import re, time, getopt, os, sys, pwd, stat;
SSHAuthSplit = re.compile('^(.* )?(\d+) (\d+) (\d+) ?(.+)$');
while (1):
- File = string.strip(sys.stdin.readline());
+ File = sys.stdin.readline().strip()
if File == "":
break;
Forward = open(File,"r");
Lines = [];
while (1):
- Line = string.strip(Forward.readline());
+ Line = Forward.readline().strip()
if Line == "":
break;
if Line[0] == '#' or Line[0] == '\n':
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-import string, re, time, ldap, getopt, sys, os, pwd;
+import re, time, ldap, getopt, sys, os, pwd;
from userdir_ldap import *;
from userdir_gpg import *;
if Update == 0:
# New account
Details = [("uid",account),
- ("objectClass",
- ("top","inetOrgPerson","debianAccount","shadowAccount","debianDeveloper")),
+ ("objectClass", UserObjectClasses),
("uidNumber",str(uidNumber)),
("gidNumber",str(gidNumber)),
("gecos",FullName+",,,,"),
#Add user group if needed, then the actual user:
if UserGroup == 1:
Dn = "gid=" + account + "," + BaseDn;
- l.add_s(Dn,[("gid",account), ("gidNumber",str(gidNumber)), ("objectClass",("top", "debianGroup"))]);
+ l.add_s(Dn,[("gid",account), ("gidNumber",str(gidNumber)), ("objectClass", GroupObjectClasses)])
l.add_s(Dn,Details);
else:
# Send the Welcome message
print "Sending Welcome Email"
-Reply = TemplateSubst(Subst,open(TemplatesDir+"/welcome-message-"+gidNumber,"r").read());
+Reply = TemplateSubst(Subst,open(TemplatesDir + "/welcome-message-%d" % gidNumber, "r").read())
Child = os.popen("/usr/sbin/sendmail -t","w");
#Child = os.popen("cat","w");
Child.write(Reply);
# ldapimport -s /etc/shadow -g /etc/group
#
-import string, re, time, ldap, getopt, sys;
+import re, time, ldap, getopt, sys;
from userdir_ldap import *;
DoAdd = 0;
Gecos[3] + "," + Gecos[4];
return (Field,cn,mn,sn);
-# Check if a number string is really a number
-def CheckNumber(Num):
- for x in Num:
- string.index(string.digits,x);
-
# Read the passwd file into the database
def DoPasswd(l,Passwd):
# Read the passwd file and import it
Split = re.split("[:\n]",Line);
(Split[4],cn,mn,sn) = ParseGecos(Split[4]);
- CheckNumber(Split[2]);
- CheckNumber(Split[3]);
- Rec = [(ldap.MOD_REPLACE,"uid",Split[0]),
- (ldap.MOD_REPLACE,"uidNumber",Split[2]),
- (ldap.MOD_REPLACE,"gidNumber",Split[3]),
- (ldap.MOD_REPLACE,"gecos",Split[4]),
- (ldap.MOD_REPLACE,"homeDirectory",Split[5]),
- (ldap.MOD_REPLACE,"loginShell",Split[6]),
- (ldap.MOD_REPLACE,"cn",cn),
- (ldap.MOD_REPLACE,"mn",mn),
- (ldap.MOD_REPLACE,"sn",sn)];
+ Split[2] = int(Split[2])
+ Split[3] = int(Split[3])
+ Rec = [("uid",Split[0]),
+ ("uidNumber",Split[2]),
+ ("gidNumber",Split[3]),
+ ("gecos",Split[4]),
+ ("homeDirectory",Split[5]),
+ ("loginShell",Split[6]),
+ ("cn",cn),
+ ("sn",sn)];
+
+ # Avoid schema check complaints when mn is empty
+ if (mn):
+ Rec.append(("mn",mn))
Dn = "uid=" + Split[0] + "," + BaseDn;
- print "Importing",Dn,
+ print "Importing", Dn
sys.stdout.flush();
- # Unfortunately add_s does not take the same args as modify :|
+ DoModify = True
+
if (DoAdd == 1):
try:
- l.add_s(Dn,[("uid",Split[0]),
- ("objectClass","top"),
- ("objectClass","account"),
- ("objectClass","posixAccount"),
- ("objectClass","shadowAccount"),
- ("objectClass","debiandeveloper")]);
+ AddRec = Rec
+ Rec.append(("objectClass", UserObjectClasses))
+ l.add_s(Dn,AddRec)
+ DoModify = False
+
except ldap.ALREADY_EXISTS:
print "exists",;
- # Send the modify request
- l.modify(Dn,Rec);
- Outstanding = Outstanding + 1;
- Outstanding = FlushOutstanding(l,Outstanding,1);
- print "done";
+ if (DoModify):
+ # Send the modify request
+ ModRec = [(ldap.MOD_REPLACE, k[0], k[1]) for k in Rec]
+ l.modify(Dn,ModRec);
+ Outstanding = Outstanding + 1;
+ Outstanding = FlushOutstanding(l,Outstanding,1);
+ print "done";
+
FlushOutstanding(l,Outstanding);
# Read the shadow file into the database
continue;
for x in range(2,8):
- CheckNumber(Split[x]);
+ Split[x] = int(Split[x])
Rec = [(ldap.MOD_REPLACE,"shadowLastChange",Split[2]),
(ldap.MOD_REPLACE,"shadowMin",Split[3]),
(ldap.MOD_REPLACE,"shadowMax",Split[4]),
- (ldap.MOD_REPLACE,"shadowWarning",Split[5]),
- (ldap.MOD_REPLACE,"shadowInactive",Split[6]),
- (ldap.MOD_REPLACE,"shadowExpire",Split[7])];
+ (ldap.MOD_REPLACE,"shadowWarning",Split[5])]
+
+ # Avoid schema violations
+ if (Split[6]):
+ Rec.append((ldap.MOD_REPLACE,"shadowInactive",Split[6]))
+
+ if (Split[7]):
+ Rec.append((ldap.MOD_REPLACE,"shadowExpire",Split[7]))
+
if (WritePasses == 1):
Rec.append((ldap.MOD_REPLACE,"userPassword","{crypt}"+Split[1]));
# Split up the group information
Split = re.split("[:\n]",Line);
Members = re.split("[, ]*",Split[3]);
- CheckNumber(Split[2]);
+ Split[2] = int(Split[2])
# Iterate over the membership list and add the membership information
# To the directory
if (DoAdd == 1):
try:
l.add_s(Dn,[("gid",Split[0]),
- ("objectClass","top"),
- ("objectClass","posixGroup")]);
+ ("objectClass", GroupObjectClasses)])
except ldap.ALREADY_EXISTS:
print "exists",;
# DGMS -> DD DDD + (MM + (SS.SSSSSS)/60)/60
# For Latitude + is North, for Longitude + is East
-import string, re, time, ldap, getopt, sys, pwd, os, posix;
+import re, time, ldap, getopt, sys, pwd, os, posix;
from userdir_ldap import *;
Anon = 0;
# packets so I can tell if a signature is made by pgp2 to enable the
# pgp2 encrypting mode.
-import string, mimetools, multifile, sys, StringIO, os, tempfile, re;
+import mimetools, multifile, sys, StringIO, os, tempfile, re;
import rfc822, time, fcntl, anydbm
# General GPG options
while 1:
x = mf.readline();
if not x: break;
- if len(string.strip(x)) != 0:
+ if len(x.strip()) != 0:
raise Error,"Unsigned text in message (at start)";
mf.seek(Pos);
InnerMsg = mimetools.Message(mf);
if InnerMsg.gettype() != "application/pgp-signature":
raise Error, "Invalid pgp/mime encoding [wrong signature type]";
- Signature = string.joinfields(mf.readlines(),'');
+ Signature = ''.join(mf.readlines())
# Check the last bit of the message..
if Paranoid != 0:
while 1:
x = mf.readline();
if not x: break;
- if len(string.strip(x)) != 0:
+ if len(x.strip()) != 0:
raise Error,"Unsigned text in message (at end)";
mf.seek(Pos);
Output = "-----BEGIN PGP SIGNED MESSAGE-----\r\n";
# Semi-evil hack to get the proper hash type inserted in the message
if Msg.getparam('micalg') != None:
- Output = Output + "Hash: MD5,SHA1,%s\r\n"%(string.upper(Msg.getparam('micalg')[4:]));
+ Output = Output + "Hash: MD5,SHA1,%s\r\n"%(Msg.getparam('micalg')[4:].upper())
Output = Output + "\r\n";
- Output = Output + string.replace(Signed.getvalue(),"\n-","\n- -") + Signature;
+ Output = Output + Signed.getvalue().replace("\n-","\n- -") + Signature
return (Output,1);
else:
if Paranoid == 0:
# Just return the message body
- return (string.joinfields(Msg.fp.readlines(),''),0);
+ return (''.join(Msg.fp.readlines()),0);
Body = "";
State = 1;
for x in Msg.fp.readlines():
Body = Body + x;
- Tmp = string.strip(x);
+ Tmp = x.strip()
if len(Tmp) == 0:
continue;
if Why == None:
GoodSig = 1;
KeyID = Split[2];
- Owner = string.join(Split[3:],' ');
+ Owner = ' '.join(Split[3:])
# Bad signature response
if Split[1] == "BADSIG":
os.mkdir(dir, 0700)
try:
- Strm = os.popen(string.join(Args," "),"r");
+ Strm = os.popen(" ".join(Args),"r")
while(1):
# Grab and split up line
Line = Strm.readline();
if Line == "":
break;
- Split = string.split(Line,":");
-
- # Store some of the key fields
+ Split = Line.split(":")
+
+ # Store some of the key fields
if Split[0] == 'pub':
KeyID = Split[4];
Owner = Split[9];
- Length = int(Split[2]);
+ Length = int(Split[2]);
# Output the key
if Split[0] == 'fpr':
# Perform a substition of template
def TemplateSubst(Map,Template):
for x in Map.keys():
- Template = string.replace(Template,x,Map[x]);
+ Template = Template.replace(x, Map[x])
return Template;
# The replay class uses a python DB (BSD db if avail) to implement
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# Some routines and configuration that are used by the ldap progams
-import termios, re, string, imp, ldap, sys, crypt, rfc822;
+import termios, re, imp, ldap, sys, crypt, rfc822;
import userdir_gpg
try:
Ech_MainLog = ConfModule.ech_mainlog;
# Break up the keyring list
-userdir_gpg.SetKeyrings(string.split(ConfModule.keyrings,":"));
+userdir_gpg.SetKeyrings(ConfModule.keyrings.split(":"))
# This is a list of common last-name prefixes
LastNamesPre = {"van": None, "von": None, "le": None, "de": None, "di": None};
"nogroup": 65534
}
+# ObjectClasses for different object types
+UserObjectClasses = ("top", "inetOrgPerson", "debianAccount", "shadowAccount", "debianDeveloper")
+RoleObjectClasses = ("top", "debianAccount", "shadowAccount", "debianRoleAccount")
+GroupObjectClasses = ("top", "debianGroup")
+
# SSH Key splitting. The result is:
# (options,size,modulous,exponent,comment)
SSHAuthSplit = re.compile('^(.* )?(\d+) (\d+) (\d+) ?(.+)$');
# Split up a name into multiple components. This tries to best guess how
# to split up a name
def NameSplit(Name):
- Words = re.split(" ",string.strip(Name));
+ Words = re.split(" ", Name.strip())
# Insert an empty middle name
if (len(Words) == 2):
Words.append('');
# Merge any of the last name prefixes into one big last name
- while LastNamesPre.has_key(string.lower(Words[-2])):
+ while LastNamesPre.has_key(Words[-2].lower()):
Words[-1] = Words[-2] + " " + Words[-1];
del Words[-2];
# If the name is multi-word then we glob them all into the last name and
# do not worry about a middle name
if (len(Words) > 3):
- Words[2] = string.join(Words[1:]);
+ Words[2] = " ".join(Words[1:])
Words[1] = "";
- return (string.strip(Words[0]),string.strip(Words[1]),string.strip(Words[2]));
+ return (Words[0].strip(), Words[1].strip(), Words[2].strip());
# Compute a random password using /dev/urandom
def GenPass():
# Convert a lat/long attribute into Decimal degrees
def DecDegree(Posn,Anon=0):
Parts = re.match('[-+]?(\d*)\\.?(\d*)',Posn).groups();
- Val = string.atof(Posn);
+ Val = float(Posn);
if (abs(Val) >= 1806060.0):
raise ValueError,"Too Big";
I = I + 4;
else:
Res = Str;
- return string.strip(Res);
+ return Res.strip()
# Take an email address and split it into 3 parts, (Name,UID,Domain)
def SplitEmail(Addr):
# Is not an email address at all
- if string.find(Addr,'@') == -1:
+ if Addr.find('@') == -1:
return (Addr,"","");
Res1 = rfc822.AddrlistClass(Addr).getaddress();
# If there is no @ then the address was not parsed well. Try the alternate
# Parsing scheme. This is particularly important when scanning PGP keys.
- Res2 = string.split(Res1[1],"@");
+ Res2 = Res1[1].split("@");
if len(Res2) != 2:
Match = AddressSplit.match(Addr);
if Match == None:
# deals with special purpose keys like 'James Troup (Alternate Debian key)'
# Some people put their names backwards on their key too.. check that as well
if len(Attrs) == 1 and \
- (string.find(string.lower(sn),string.lower(Attrs[0][1]["sn"][0])) != -1 or \
- string.find(string.lower(cn),string.lower(Attrs[0][1]["sn"][0])) != -1):
+ ( sn.lower().find(Attrs[0][1]["sn"][0].lower()) != -1 or \
+ cn.lower().find(Attrs[0][1]["sn"][0].lower()) != -1 ):
Stat = EmailAppend+" hit for "+str(Name);
return (Name[1],[Stat]);