Categories
Coding

Creating *NIX user accounts without need for a password prompt!

It is likely that in future I will be implementing SSH access and generally changing the way that users are handled by ZPanel (on the *NIX platform). Currently all user accounts across ZPanel are ‘virtual’ accounts and not system accounts and for various reason’s I may want to change this in future.

I have written a handle shell script to automate the system account creation of users on *NIX – I thought I’d post this up as an example:-

#!/bin/bash
# Script to add a user to *NIX system by Bobby Allen, 14/11/2012
if [ $(id -u) -eq 0 ]; then
 read -p "Enter username: " username
 read -s -p "Enter password: " password
 egrep "^$username" /etc/passwd >/dev/null
 if [ $? -eq 0 ]; then
 echo "$username exists!"
 exit 1
 else
 pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
 useradd -m -p $pass $username
 [ $? -eq 0 ] && echo "User has been added to this system!" || echo "Failed to add the user!"
 fi
else
 echo "Only root isp permitted add a user to this system"
 exit 2
fi

Obviously the cool thing about this shell script is that it can be used to generate user accounts without the requirement for human interaction ie. when prompted for the password 🙂

The above shell script requires perl to be installed as it uses the perl crypt() function to generate a UNIX hash for the given password.

Although the above code is alot larger than it needs to be I just wanted to demonstrate the as a ‘copy & paste’ example.

The main magic is done here:-

useradd -m -p encryptedPassword username

But is important that you check that the username is not already taken etc. first and the generation of the encrypted password.