26285 total geeks with 3498 solutions
Recent challengers:
 Welcome, you are an anonymous user! [register] [login] Get a yourname@osix.net email address 

Articles

GEEK

User's box
Username:
Password:

Forgot password?
New account

Shoutbox
MaxMouse
It's Friday... That's good enough for me!
CodeX
non stop lolz here but thats soon to end thanks to uni, surely the rest of the world is going good?
stabat
how things are going guys? Here... boring...
CodeX
I must be going wrong on the password lengths then, as long as it was done on ECB
MaxMouse
lol... the key is in hex (MD5: of the string "doit" without the "'s) and is in lower case. Maybe i should have submitted this as a challenge!

Donate
Donate and help us fund new challenges
Donate!
Due Date: May 31
May Goal: $40.00
Gross: $0.00
Net Balance: $0.00
Left to go: $40.00
Contributors


News Feeds
The Register
40 Gbps wireless
designed to
complement fibre
rollouts
Anonymous threat
shutters Gitmo WiFi
Dev writes comments
as limericks and
other coding
secrets
Opera comes to
Android
James Bond inspires
US bill to require
smart guns for all
COLD FUSION is BACK
with "anomolous
heat" claim
Startup hires
"cyborg" Mann for
Google Glass?killer
project
Soylent Corporation
prepares to DEFEAT
FOOD
VMware public cloud
aims at ESXi
customers, not AWS
Microsoft reveals
Xbox One, the
console that can
read your heartbeat
Slashdot
Google Chrome 27 Is
Out: 5% Faster Page
Loads
Special Ops Takes
Its Manhunts Into
Space
Aurora Attackers
Were Looking For
Google"s
Surveillance
Database
Dart Is Not the
Language You Think
It Is
EPA Makes a Rad
Decision
Ask Slashdot: Can
Yahoo Actually
Stage a Comeback?
3-D Printable Food
Gets Funding From
NASA
Transporting a
15-Meter-Wide,
600-Ton Magnet
Cross Country
House Bill Would
Mandate Smart Gun
Tech By U.S.
Manufacturers
Do Developers Need
Free Perks To
Thrive?
Article viewer

Bash adduser script to generate Linux useradd syntax strings



Written by:typedeaF
Published by:Obscurity
Published on:2004-08-12 14:50:25
Topic:Linux
Search OSI about Linux.More articles by typedeaF.
 viewed 40322 times send this article printer friendly

Digg this!
    Rate this article :
This script is a skeleton for creating useradd strings.
Use this script in Linux environments where several types of users have specific account credentials, or add it to a pseudo-list for junior admins or less privilaged accounts so they can safely handle useradd tasks.

#!/bin/bash
# adduser - build a useradd string and a password for passwd
# by typedeaF
# grep -v '^#' thisfile.sh | less to strip the comments

# Make a semi-random password using an array of user-friendly characters
function mkpass() {
  PASS=""
  PASSLEN=8
  array1=( q w e r t y u i o p a s d f g h j k l z x c v b n m
    Q W E R T Y U I O P A S D F G H J K L Z X C V B N M
    1 2 3 4 5 6 7 8 9 0 \! \@ \# \$ \% \^ \& \* \( \)
  )
  MODNUM=${#array1[*]}

  count=0
  while [ ${count:=0} -lt $PASSLEN ]
  do
    number=$(($RANDOM%$MODNUM))
    PASS="$PASS""${array1[$number]}"
    ((count++))
  done

  echo $PASS
}

# center the text on the screen by finding the horizontal center with max_lines
# max_lines divided by two becomes the center line(aka. line_num)
# use the max lenght of the line divided in half to find the center column
# subtract half the output string from the center to create the offset to indent
function center_txt() {
  PROMPT="$1"
  str_len=${#PROMPT}
  indent=$(( ((max_cols / 2)) - ((str_len / 2)) ))
  line_num=$(( max_lines / 2 ))
  tput cup ${line_num} ${indent}
  echo "$PROMPT"
}

# indent_txt is intended to be used AFTER center_txt
# indent_txt just prints on the current line and centers the text horizontally
# line_num is global, so main keeps track of incrementing it
function indent_txt() {
  PROMPT="$1"
  str_len=${#PROMPT}
  indent=$(( ((max_cols / 2)) - ((str_len / 2)) ))
  tput cup ${line_num} ${indent}
  echo "$PROMPT"
}

# mk_prompt creates an input prompt for the the read function
# 'read -p "==> " variable' would work, but I like this better
function mk_prompt() {
  ((line_num+=2))
  tput cup $line_num 15
  PROMPT="==> "
  echo -n "${blink}${PROMPT}"
  echo -n ${offblink}
}

# This function gathers all the information needed to generate the useradd string
function mkuser() {
  USERNAME=""
  FULLNAME=""
  EXPIRE=""
  GROUP=""
  HOME=""

  echo ${term_clr}
  PROMPT="Enter the new Login account name"
  center_txt "$PROMPT"
  ((line_num++))
  PROMPT="(ex. typedeaf)"
  indent_txt "$PROMPT"
  mk_prompt
  read USERNAME

  echo ${term_clr}
  PROMPT="Enter the users Full Name"
  center_txt "$PROMPT"
  ((line_num++))
  PROMPT="(ex. Mister typedeaF)"
  indent_txt "$PROMPT"
  mk_prompt
  read FULLNAME

  echo ${term_clr}
  PROMPT="Select the users Primary Group"
  center_txt "$PROMPT"
  ((line_num++))
  PROMPT="(ex. type \"1\" for Primary Group staff)"
  indent_txt "$PROMPT"
  ((line_num+=2))
  indent=$(( ((max_cols / 2)) - 6 ))
  tput cup $line_num $indent; ((line_num++)); echo "1) staff"
  tput cup $line_num $indent; ((line_num++)); echo "2) faculty"
  tput cup $line_num $indent; ((line_num++)); echo "3) parttime"
  tput cup $line_num $indent; ((line_num++)); echo "4) adjunct"
  mk_prompt
  read REPLY

  case "$REPLY" in
  1)
    GROUP="staff"
    HOME="/home/$GROUP/$USERNAME"
    # add some staff specific stuff here
    ;;
  2)
    GROUP="faculty"
    HOME="/home/$GROUP/$USERNAME"
    # add some faculty specific stuff here
    ;;
  4)
    GROUP="adjunct"
    HOME="/home/$GROUP/$USERNAME"
    # add some adjunct specific stuff here
    ;;
  3)
    GROUP="parttime"
    HOME="/home/$GROUP/$USERNAME"
    echo ${term_clr}
    PROMPT="Enter the Expiration Date"
    center_txt "$PROMPT"
    ((line_num++))
    PROMPT="(ex. 2004-06-30 for June 30th 2004)"
    indent_txt "$PROMPT"
    mk_prompt
    read EXPIRE
    ;;
  * )
    echo "Invalid choice"
    ;;
  esac
}

# Just reset the terminal to normal
function _quit() {
  reset -Q
  echo "Exiting addfas.sh. Bye"
  exit 0
}


# =================================================#
# Begin Main #
# =================================================#

# These are the tput commands used to terminal output formatting
term_clr=$(tput clear)
max_lines=$(tput lines)
max_cols=$(tput cols)
blink=$(tput blink)
offblink=$(tput sgr0)

let CONTINUE=0

# Set up a trap to handle control signals. If you start using temp files then
# this is where you would want to clean up.
trap _quit INT TERM QUIT

# This could just as easily been while [ TRUE ], but the CONTINUE sentinal
# is included for flexability.
while [ $CONTINUE -eq 0 ]
do
  mkuser
  echo ${term_clr}
  PROMPT="User added with the following criteria"
  center_txt "$PROMPT"
  ((line_num+=2))

# There are more complex ways to handle this, like with the tertiary expr?expr:expr
# syntax, but it only makes things more complex looking at the sake of saving a
# few key strokes. Notice that using something like ${EXPIRE+-e$EXPIRE}
# doesnt work quite like expected. Instead of trying to cut corners and make 'leet'
# code, just keep it simple.
  if [ -z "$EXPIRE" ]; then
    PROMPT="useradd -c\"$FULLNAME\" -d$HOME -g$GROUP $USERNAME"
    indent_txt "$PROMPT"
    ((line_num+=2))
  else
    PROMPT="useradd -c\"$FULLNAME\" -d$HOME -e$EXPIRE -g$GROUP $USERNAME"
    indent_txt "$PROMPT"
    ((line_num+=2))
  fi
  uline=$(tput smul)
  offuline=$(tput rmul)
  PROMPT="Recommended Password:"
# I confess, I couldn't find a way to get $PASSLEN to parse correctly so I gave up
# and used the variable constant '8'.
  str_len=$(( ${#PROMPT} + 8 ))
  indent=$(( ((max_cols / 2)) - ((str_len / 2)) ))
  tput cup ${line_num} ${indent}
  echo -n "${uline}$PROMPT${offuline} "
  mkpass
  tput cup $max_lines
# Here is where you might want to include your CONTINUE sentinal.
# Like: if [ "$REPLY" = "x" ]; then CONTINUE=1; fi
  PROMPT="Press Return to continue. Press ^C to EXIT."
  echo -n "${blink}${PROMPT}"
  echo -n ${offblink}
  read -s
done

# reset your signal traps
trap - INT TERM QUIT
exit 0


This script is more of a skeleton. The groups I included are just to give you an idea of how things might differ. In this script, parttime users have an expiration date set. Other things that would be common is changing their home directories, adding public_html directories, assigning various groups, adding particular paths to PATH, etc. Keep in mind that things ALL users should get assingned should be in the /etc/skel file.

This program plays it safe and just echos the useradd line, you can easily modify this to execute the command and check for a return status. Other things missing...well there is a total lack of input validation. If you take for granted that an admin should be using this, and that the examples are clear enough, then input validation should not be an issue. Input validation could be done by placing each read inside a loop and checking the $REPLY variable with expr $REPLY : '/some regex/'. Lastly, good UNIX programming practice stresses that critical information be written to stderr. You might consider altering each echo to redirect to stderr with the >&2 syntax.

If you haven't noticed, this program builds on the last article/script I published that generates random passwords. Read that article for information on how the password generation works. I use scripts like these all the time to help me generate long command line strings or for maintaining flat database files. This script makes good use of many of the advanced features of bash scripting.

Since bash will treat almost all variables as globals, it is important to initilize variables back to NULL or 0 at the begining of each iteration. You dont want your counters starting off at non zero numbers, etc.

Sorry for the lack of documentation. Using help bash_command or man bash is a good place to start if you are lost on something.

tF

Did you like this article? There are hundreds more.

Comments:
fianna
2004-11-02 08:47:56
sweat...
Anonymous
2006-07-28 08:09:10
can we use it to manage users to WHEELL group ?
Anonymously add a comment: (or register here)
(registration is really fast and we send you no spam)
BB Code is enabled.
Captcha Number:


Blogs: (People who have posted blogs on this subject..)
bb
start svn on system boot in debian on Tue 21st Jul 10am
http://linux.justinhartman.com/Startup_S cript_for_Subversion I found this a really simple explanation of how to start svn when the server boots
bb
SSHFS: Super Easy File Access over SSH on Wed 18th Feb 1pm
This was really useful, and worked great to communicate between servers. http://www.linuxjournal.com/article/8904 Thanks to gabbs
bb
hellanzb nzb news downloader for NSLU2 on Tue 22nd May 7pm
Someone introduced me to the joyful NZB file recently. Its truly a wonderful invention, and allows my to explore usenet binary grabbing using my NSLU2. as previous nntp readers id tried made the process too painful. So simply .... 1) apt-get inst
bb
edna mp3 streaming for nslu2 on Wed 9th May 11am
I've been streaming music from my home NSLU2 server for a while now using mt-daapd (firefly) which is an ITunes server for linux. I can connect to my home network from work using ITunes and a little daap proxy app called rendevous. My friend was doing
Adnurak
How to choose the right Linux Distro on Thu 9th Nov 7pm
This is mainly for new users who want to try out Linux for the first time, but try it out if you're experienced in Linux anyway, it's kinda fun. What with all these different distributions of Linux that you hear about all the time, it's hard to choose
ketan404
my blog on Thu 9th Nov 6am
http://ketan404.blogspot.com
bb
Tweaking Apache and Mysql for Low Memory on Fri 20th Oct 11am
i implemented this to tweak my apache/mysql for better performance on my NSLU2. Hard to tell if its helping much though ;-) Mysql really doesnt run too well with apache on NSLU2 so I dont use it for much. http://www.unixshell.com/wiki/index.php/ Optimiz
Adnurak
Fate - A Linux Security Simulation Written in C++ on Fri 20th Oct 6am
Fate is a simulation of a Linux system written in C++ and meant for DOS (runs fine in winxp and winme by just doubleclicking) that according to the creator, m101, shows you the basics of security in different Linux systems, including but not limited to, M
bb
Article on building rtorrent for arm5vtel NSLU2 with debianslug on Thu 19th Oct 7am
I wrote an article today on my efforts at compiling rtorrent for debianslug. its here ... Article on building rtorrent/libtorrent for arm5vtel NSLU2 with littleendian debianslug
bb
How to mount .iso file on NSLU2 running debianslug on Tue 19th Sep 12pm
If like me your running debianslug on an NSLU2 and you'd like to mount an iso file so it can be directly streamed to Xbox Media Centre (its a beautiful solution isnt it!) then simply do the following. Ensure you have loop support in your debianslug k

Test Yourself: (why not try testing your skill on this subject? Clicking the link will start the test.)
Linux Test Simple by a13x4nd7u

This is a simple Linux commands test.
Linux Quiz by abhijangda

Trivia about your favorite OS
Linux Administration by typedeaF

Testing your knowledge of Linux administration tools, very light shell scripting, and good high level understanding of how the OS works at the user level. Anyone who has worked with Linux for 1-3 years should do good.
Linux Commands (Part 1) by nirus

If you think you know the linux command-line then this test is for you. For reference purposes, it is based on Debian/GNU Linux with a BASH Shell.


     
Your Ad Here
 
Copyright Open Source Institute, 2006