views:

1225

answers:

6

I need to have the ability to create user accounts on my Linux ( Fedora 10 ) and automatically assign a password via a bash script ( or otherwise, if need be ).

It's easy to create the user via Bash eg:
[whoever@server ]# /usr/sbin/useradd newuser

But is it possible to assign a password in Bash, something functionally similar to this (but automated):

[whoever@server ]# passwd newuser
Changing password for user testpass.
New UNIX password:
Retype new UNIX password:
passwd: all authentication tokens updated successfully.
[whoever@server ]#

A: 

Try adduser instead of useradd

As chinmay pointed out, this is a debian/ubuntu thing, but perhaps you can borrow the script from the page that he linked to

adduser can also do useful thing like adding the user to groups

gnibbler
On Fedora, adduser is simply a symlink to useradd. http://www.go2linux.org/useradd-vs-adduser
Chinmay Kanchi
+3  A: 

You can use the -p option.

useradd -p encrypted_password newuser

Unfortunately, this does require you to hash the password yourself (where passwd does that for you). Unfortunately, there does not seem to be a standard utility to hash some data so you'll have to write that yourself.

Here's a little Python script I whipped up to do the encryption for you. Assuming you called it pcrypt, you would then write your above command line to:

useradd -p $(pcrypt ${passwd}) newuser

A couple of warnings to be aware of.

  1. While pcrypt is running, the plaintext will be visible to any user via the ps command.
  2. pcrypt uses the old style crypt function - if you are using something more moderns like an MD5 hash, you'll need to change pcrypt.

and here's pcrypt:

#!/usr/bin/env python

import crypt
import sys
import random

saltchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

def salt():
    return random.choice(saltchars) + random.choice(saltchars)

def hash(plain):
    return crypt.crypt(arg, salt())

if __name__ == "__main__":
    random.seed()
    for arg in sys.argv[1:]:
        sys.stdout.write("%s\n" % (hash(arg),))
R Samuel Klatchko
Thanks R Klatchko, That should work. I can't believe I didn't know about the -p option. I can take care of hashing myself:)
ModernCarpentry
perl -e 'print crypt($ARGV[0], "password")' 'mypassword'
threecheeseopera
+1  A: 

You can use expect in your bash script.

From http://www.seanodonnell.com/code/?id=21

#!/usr/bin/expect 
######################################### 
#$ file: htpasswd.sh 
#$ desc: Automated htpasswd shell script 
######################################### 
#$ 
#$ usage example: 
#$ 
#$ ./htpasswd.sh passwdpath username userpass 
#$ 
###################################### 

set htpasswdpath [lindex $argv 0] 
set username [lindex $argv 1] 
set userpass [lindex $argv 2] 

# spawn the htpasswd command process 
spawn htpasswd $htpasswdpath $username 

# Automate the 'New password' Procedure 
expect "New password:" 
send "$userpass\r" 

expect "Re-type new password:" 
send "$userpass\r"
Carlos Tasada
Cool! This'll work as well~
ModernCarpentry
+3  A: 

You can run the passwd command and send it piped input. So, do something like:

echo thePassword | passwd theUsername --stdin
Tralemonkey
Bonus of that method is that it's secure (assumed `echo` is a builtin in the used shell, which it is commonly), at least concerning `/proc/`.
Marian
+1  A: 

I was asking myself the same thing... and didn't want to rely on a python script. So this is the line to add a user with a defined password in one bash line!

/usr/sbin/useradd -p `openssl passwd -crypt $PASS` $USER

Damien
A: 

Here is a script that will do it for you .....

You can add a list of users (or just one user) if you want, all in one go and each will have a different password. As a bonus you are presented at the end of the script with a list of each users password. .... If you want you can add some user maintenance options

like:

chage -m 18 $user
chage -M 28 $user

to the script that will set the password age and so on.

=======

#!/bin/bash

# Checks if you have the right privileges
if [ "$USER" = "root" ]
then

# CHANGE THIS PARAMETERS FOR A PARTICULAR USE
PERS_HOME="/home/"
PERS_SH="/bin/bash"

   # Checks if there is an argument
   [ $# -eq 0 ] && { echo >&2 ERROR: You may enter as an argument a text file containing users, one per line. ; exit 1; }
   # checks if there a regular file
   [ -f "$1" ] || { echo >&2 ERROR: The input file does not exists. ; exit 1; }
   TMPIN=$(mktemp)
   # Remove blank lines and delete duplicates 
   sed '/^$/d' "$1"| sort -g | uniq > "$TMPIN"

   NOW=$(date +"%Y-%m-%d-%X")
   LOGFILE="AMU-log-$NOW.log"

   for user in $(more "$TMPIN"); do
      # Checks if the user already exists.
      cut -d: -f1 /etc/passwd | grep "$user" > /dev/null
      OUT=$?
      if [ $OUT -eq 0 ];then
         echo >&2 "ERROR: User account: \"$user\" already exists."
         echo >&2 "ERROR: User account: \"$user\" already exists." >> "$LOGFILE"
      else
         # Create a new user
         /usr/sbin/useradd -d "$PERS_HOME""$user" -s "$PERS_SH" -m "$user"
         # passwdgen must be installed
         pass=$(passwdgen -paq --length 8)
         echo $pass | passwd --stdin $user
         # save user and password in a file
         echo -e $user"\t"$pass >> "$LOGFILE"
         echo "The user \"$user\" has been created and has the password: $pass"
      fi
   done
   rm -f "$TMPIN"
   exit 0
else
   echo >&2 "ERROR: You must be a root user to execute this script."
   exit 1
fi

===========

Hope this helps.

Cheers, Carel

Carel Lubbe