13,420
edits
Changes
no edit summary
<code style="color:#3366CC;font-family:courier;font-size:.9em;margin-left:20px;">
<br>
<br>
# createUsers.bash<br># Purpose: Generates a batch of user accounts (user data stored in a text file)<br>#<br># USAGE:<br>#<br># /root/createUsers.bash [-i {input-path}] [-n {full name}] [-a {aging}] [-g {add to group}] [-o {output-path}]<br>#<br># Author:*** INSERT YOUR NAME ***<br># Date: *** CURRENT DATE ***<br><br>if [ $HOME != "root" ] # only runs if logged in as root<br>::then<br> echo "You must be logged in as root." >&2<br>:: exit 1<br>::fi<br>
</code>
<br>
<br>
<code style="color:#3366CC;font-family:courier;font-size:.9em;">
<br>::outputFlag="n"<br>::while getopts i:n:a:g:o: name<br>::do<br>:: case $name in<br>:: i) inputFile=$OPTARG ;;<br>:: :) echo "Error: You need text after options requiring text"<br>:: exit 1 ;;<br>:: \?) echo "Error: Incorrect option"<br>:: exit 1 ;;<br>:: esac<br>
</code>
<ol><li value="6">Save your editing session, but remain in the text editor.</li><li>The code displayed below uses logic to exit the script if the input file does not exist. Command substitution is used to store each line of the input file as a positional parameter. There is one subtle problem here: The full names of the users contain spaces which can create havoc when trying to set each line as a separate positional parameter. In this case the sed command is used to convert spaces to plus signs (+), which will be converted back later. Finally, a '''for''' loop is used to create each account ('''useradd''') and mail the user their account information ('''mail'''). Add the following code:</li></ol>
<br>
<code style="color:#3366CC;font-family:courier;font-size:.9em;">
<br>::if [ ! -f $inputFile ]<br>::then<br>:: echo "The file pathname \"$inputFile\" is empty or does not exist" >&2<br>:: exit 2<br>::fi<br><br>::set $(sed 's/ /+/g' $inputfile) # temporarily convert spaces to + for storing lines as positional parameters<br><br>::for x<br>::do<br>:: useradd -m -c "$(echo $x | cut -d":" -f2 | sed 's/+/ /g')" -p $(date | md5sum | cut -d" " -f1) $(echo $x | cut -d":" -f1)<br>:: mail -s "Server Account Information" $(echo $x | cut -d":" -f3) <<+<br>:: Here is your server account information:<br>:: servername: myserver.senecac.on.ca<br>:: username: $(echo $x | cut -d":" -f1)<br>:: password: $(date | md5sum | cut -d" " -f1)<br>:: Regards,<br>:: IT Department<br>::+<br>::done<br><br>::echo -e "\n\nAccounts have been created\n\n"<br>::exit 0<br>
</code>