[Techtalk] help with python script for batch useradd

Carla Schroder carla at bratgrrl.com
Tue Jan 6 12:27:23 EST 2004


Er, maybe here it is, I renamed it to massadd_py.txt. Mailman doesn't like 
attachments. :)

-- 
~~~~~~~~~~~~~~~~~~~~~~~~~
Carla Schroder
www.tuxcomputing.com
this message brought to you
by Libranet 2.8 and Kmail
~~~~~~~~~~~~~~~~~~~~~~~~~
-------------- next part --------------
#!/usr/bin/env python

from string import lowercase, uppercase
from random import choice
from os import system, popen
from sys import stdin, stdout

def make_pass():
    """creates a random eight-character password from A-Za-z0-9."""
    numbers = "".join(map(str, range(10)))
    chars = lowercase + uppercase + numbers
    
    p = ""
    for r in range(8):
        p += choice(chars)

    return p

# a date in the past.  This will be the 'last password change' date.
olddate = "2003-01-01"

for line in stdin.readlines():
    line = line.strip()  # remove EOL characters
    username, realname = line.split(':')
    password = make_pass()
    
    # add the user.  Specify the real name and create a homedir, use
    # defaults for the rest.
    system("/usr/sbin/useradd -m -c \"%s\" %s" % (realname, username))
    
    # set the password.  We use popen instead of just echoing the
    # password because we don't want it to show up on a process list.
    chp = popen("/usr/sbin/chpasswd", 'w')
    chp.write("%s:%s\n" % (username, password))
    chp.close()
    
    # finally, we expire the password by setting the 'last changed'
    # date to somewhere in the past, and the expire timeout to
    # ninety days.
    system("/usr/bin/chage -M 90 -d %s %s" % (olddate, username))

    # we want to know what the password is, so we print it to stdout.
    # the sysadmin should probably redirect this to a file.
    print "%s\t%s" % (username, password)


More information about the Techtalk mailing list