[Tutor] adding users from a script

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 14 Sep 2001 16:55:22 -0700 (PDT)


On Fri, 14 Sep 2001, Cerulean Rodent wrote:

> So here we go. Thanks to everyone for the tips - I'm posting the
> functional version of the script I was working at. It might look
> pretty ugly at times - but it's the first thing halfway resembling a
> programme that I've written, so maybe all hope is not lost...

Let's take a look.


> import os
> import re
> import whrandom
> 
> rnd = whrandom.whrandom()

I see that you're creating a random number generator called "rnd".  It's
actually ok to use the choice() function of whrandom directly: Python
keeps a personal copy of whrandom.whrandom(), and uses it for
whrandom.choice().  So:

###
>>> whrandom.choice('abcdefghijklmnopquvwxyz')
'g'
###

should work as well.



> validfirst ="abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\
> 23456789"

Looks good.


> pwlen = 8
> 
> pw = ""
> 
> idx = 0
> 
> while idx < pwlen:
> 	pw = pw + rnd.choice(validfirst)
> 	idx = idx + 1


I see, so this makes up a password of length 'pwlen'.  You can also do
this with a Python 'for' loop:

###
for idx in range(pwlen):
    pw = pw + rnd.choice(validfirst)
###

which has a similar effect to the while loop, and is a line shorter.  
*grin*




> encr = os.popen('mkpasswd ' + pw + ' dread', 'r')
> z = re.sub(r'\n','',encr.read())

Good use of regular expressions to strip off newlines from input.  You can
also use the replace() method of strings:

###
z = encr.read().replace(r'\n', '')
###

if the pattern is simple enough.  Another nice string method, strip(),
will remove leading and trailing whitespace from a string:

###
z = encr.read().strip()
###



> nomme = raw_input("\nPrint your desired username:\n>>")
> 
> if nomme != '':
> 	os.system('useradd -p ' + z + ' -s /bin/false' + ' ' + '-G mail' + ' ' + nomme) 
> else:
> 	print "\nYou must enter a valid username!"

If the user doesn't enter a vaild username, you should probably continue
asking them for a good username until they give one to you.  At the
moment, your program gives a small wrist slap, but then continues on.


> logfile = open('passlog', 'a')
> 
> logfile.write(nomme + "\t" + pw + "\n")
> 
> logfile.close

Ah; use:

###
logfile.close()
###

instead --- In Python, functions don't fire off without the parentheses,
even if they don't take any arguments.  There's a reason why it's this
way, and you'll see it when you learn about "callback" functions and
functional programming in the future.



> Scary, huh? The gurus must be grinding their teeth in horror wishing
> to orally decapitate yours truly... newbies are a plague, and

Not so!  The program works, and it makes sense.  Newbies are newcomers,
and that's where all of us started from.  We're here to make Python fun,
not fearful.  And don't worry about upsetting us --- we have tough skin.  
*grin*


Thanks for sharing your program with us!