Changes

Jump to: navigation, search

OPS245 Lab 4

3,567 bytes removed, 16:02, 21 September 2021
INVESTIGATION 4: CREATING USERS VIA SHELL SCRIPTS: - replacing bash getopts investigaion with a python argparse investigation.
'''Answer INVESTIGATION 3 observations / questions in your lab log book.'''
= INVESTIGATION 4: CREATING USERS VIA USING ARGUMENTS IN SHELL SCRIPTS=
===Using argparse to Obtain Positional Arguments from the Command Line===
{|width="40%" align="right" cellpadding="10"|- valign="top"|{{Admon/tip|Bash Shell Scripting Tips:|<br>In this investigation we will use python'''T<u>he case statement</u>'''<ul><li>The case statement is a control-flow statement that works in a similar way as the if-elif-else statement (but is more concise). This statement presents scenerios or "cases" based on values or regular expressions (not ranges of values like if-elif-else statements).<br><br></li><li>After action(s) are taken for a particular scenerio (or "case"), a break statement (''';;''') is used argparse module to "break-out" of the statement (and not perform other actions). A default case (*) is also used to catch exceptions.<br><br></li><li>Examples:<br><br>''read -p "pick a door (1 or 2): " pick<br>case $pick in<br>&nbsp; 1) echo "You win a car!" ;;<br>&nbsp; 2) echo "You win a bag of dirt!" ;;<br>&nbsp; *) echo "Not a valid entry"<br>&nbsp;&nbsp;&nbsp;&nbsp; exit 1 ;;<br>esac''<br><br>''read -p "enter a single digit: " digit<br>case $digit in<br>&nbsp; [0-9]) echo "Your single digit is: $digit" ;;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; *)&nbsp;echo "not a valid single digit"<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; exit 1 ;;<br>esac''<br><br></li></ul>'''<u>The getopts function</u>'''<ul><li>The getopts function allows the shell scripter to create make our scripts that accept options (like options for Linux commands). This provides the Linux administrator with scripts that provide more flexibility and versatility. A builtautomation-in function called '''getopts''' capable by reducing (i.e. get command options) is used in conjunction with a '''while''' loop and a '''case''' statement to carry out actions based on if certain options are present when the shell script is run.<br><br></li><li> The variable '''$OPTARG''' can be used if an option accepts text (denoted in the getopts function with an option letter followed by a colon. Case statement exceptions use the ''':or eliminating)''' and '''\?)''' cases for error handling.<br><br><li>Example:<br><br>''while getopts abc: name<br>do<br>&nbsp; case $name in<br>&nbsp; &nbsp; a) echo "Action for option \"a\"" ;;<br>&nbsp; &nbsp; b) echo "Action for option \"b\"" ;;<br>&nbsp; &nbsp; c) echo "Action for option \"c\""<br>&nbsp; &nbsp; &nbsp; &nbsp; echo Value is: $OPTARG" ;;<br>&nbsp; &nbsp; :) echo "Error: You how much interactivity we need text after -c option"<br>&nbsp; &nbsp; &nbsp; &nbsp; exit 1 ;;<br>&nbsp; &nbsp; \?) echo "Error: Incorrect option"<br>&nbsp; &nbsp; &nbsp; &nbsp; exit 1 ;;<br>esac''<br>done<br><br></li></ul>}}|}===Using getopts Function &amp; case statement=== We will now use shell scripting to help automate from the task for a Linux adminstrator to create regular user accounts.
:'''Perform the following steps:'''
#<ol><li>You will be using your '''c7host''' machine for this section.#Open a shell terminal, and use <b><code><span style="color:#3366CC;font-size:1.2em;">sudo -i</spanli></codeli></b> to start a root session.#Change to the your '''/root/bin''' directory.#Download, study, and run the following shell script. Issue the command:<br/li><bli><code><span style="cursor:default;color:#3366CC;font-size:1Use your tarchiver.2em;">wget https:py command (from lab 3) to make a tar archive of //icttmp called mytmp.senecacollegetar.ca/~peter.callaghan/ops245/labs/user-create.bash<br /span></code></b>#Try You'll notice that even after hitting enter to understand what these Bash Shell scripts do, and then run the command, you still needed to give more data to your script as root (to tell it which directory you wanted to create just one user called '''test'''. After running the shell scriptarchive, what to call it, view the contents of the '''/home''' directory and what compression to confirmuse).<br />  Although Requiring this much interaction from the '''zenity''' command is a "user-friendly" way to run shell scripts, Linux administrators usually create shell scripts means that resemble common Linux commandsthis script is not very good for automation. In We can't schedule this lab, you will learn to create a shell script using the getopts function to make your shell script behave more like actual Linux commands automatically run, because we (including the use of optionsor another admin). Refer need to be present to type answers to the notes section on the right-hand-side for reference about the '''case''' statement and the '''getopts''' functionprompts.  <ol/li><li value="6">Use the wget command to download the input file called user-dataMake a copy of your tarchiver.txt by issuing the command:<br><b><code><span style="color:#3366CC;font-size:1.2em;">wget https://ictpy script and call it tarchiver2.senecacollegepy.ca/~peter We will work with tarchiver2.callaghan/ops245/labs/user-datapy for the rest of this investigation.txt</spanli></code></bli>Import the argparse module into tarchiver2.py.</li><li>View Add the contents on the user-data.txt file following lines to confirm there are 3 fields (usernameyour script, fullnameafter the import, and e-mail address)which are separated by but before you prompt the colon (user for anything:) symbol.<br /li><li>Use a text editor (such as <b><code><span styleparser ="color:#3366CC;font-size:1argparse.2em;">viArgumentParser()<br/span>args = parser.parse_args()</code><br /b> or <b><code><span style="color:#3366CC;fontThis creates an argument parser and makes it read all the command line arguments the user entered. However, we haven't defined any that we expect yet, so all this will do is display a default help message if the user runs our script with -size:1h.2em;">nano</spanli></codeli>Try that now:<br /b>) to create a Bash Shell script called: <b><code><span style="color:#3366CC;fonttarchiver2.py -size:1.2em;">createUsers.bashh</spancode></codeli></bli> in the /root/bin directoryFor argparse to be really useful, we need to tell it to expect some command line arguments (and then do something with them).<br /li><li>Enter Modify your script so the following text content into your text-editing sessionargparse portion of it looks like this:<br /li></ol><code style>parser ="color:#3366CC;font-family:courier;font-size:argparse.9em;margin-left:20px;font-weight:bold;">ArgumentParser()<br>&#35;!/bin/bash <br>parser.add_argument("dest",help="The name you would like to give the archive.")<br/>&#35; createUsersargs = parser.bash<br>&#35; Purpose: Generates a batch of user accounts parse_args(user data stored in a text file)<br>&#35;<br>&#35; USAGE: /root/createUsers.bash [-i {input-path}] <brcode>&#35;<br/>&#35; AuthorAnd replace the line where you prompt the user for the destination archive name with: *** INSERT YOUR NAME ***<br/>&#35; Date: *** CURRENT DATE ***<brcode>destination = args.dest<br/code>&#35; Make certain user is logged in as root<br/>if [ $(whoami) != "root" ]<br>then<br>&nbsp; &nbsp;echo "Note: You are required Instead of '''destination''', use the variable name were already using to store the value you were getting from the user. That way you won't have to run this program as rootchange it in the rest of your script."<br/li>&nbsp; &nbsp;exit 1<brli>fiTry using your script to make another archived copy of /tmp, this time calling it secondtmp.tar.<br/><br>if [ "$#" -eq 0 ] # If you didn't provide secondtmp.tar on the command line when you ran the command, you'll notice that your script complained. if no arguments after command<br>then<br>&nbsp;echo "You must enter an argument" >&2<br>&nbsp;echo "USAGETry running: $0 [-i {input-path}]" >&2<br/>&nbsp;exit 2<brcode>fi<br>tarchiver.py secondtmp.tar</code><br/li><ol><li value="12">Save your editing sessionYou should still be getting prompted about the directory you want to archive, and whether or not you want compression, but remain in you are now telling the script that the text editorcreated archive should be called secondtmp.tar.</li><li>The code displayed below uses Run the script again, but this time give the archive a different name of your own choice. Your script is part way to being automatable: the getopt function user can set the input file pathname or check name of the created archive before the script runs. We just need to make this possible for invalid options or missing option textthe rest of the required data. Add the following code</li></ol><brli><code style="color:#3366CC;font-family:courier;font-size:Add a second parser.9em;font-weight:bold;"><br>outputFlag="n"<br>while getopts i: add_argument line to your script so that you can also obtain the name<br>do<br>&nbsp;case $name in<br>&nbsp; &nbsp;i) inputFile=$OPTARG ;;<br>&nbsp; &nbsp;:) echo "Error: of the directory to archive from the command line. You need text can choose if it should go before or after options requiring text"the name of the archive. Just remember to use a different argument name, and an appropriate help message.<br/li>&nbsp; &nbsp; &nbsp; &nbsp;exit 1 ;;<brli>&nbsp; &nbsp;\?) echo "Error: Incorrect option"Replace the line in your script that prompts the user for the name of the directory with code that will retrieve the value the user entered on the command line.<br>&nbsp; &nbsp; &nbsp; &nbsp; exit 1 ;;<br/li>&nbsp;esac<brli>doneRun you script to make sure it works.<br></code><ol><li value="14">Save your editing sessionYou should now be able to enter both the directory to archive, but remain in and the name of the resulting archive on the text editorcommand line, and should only be prompted about compression.</li><li>The code displayed below uses logic All that is left to exit finish the script if the input file does not exist. Command substitution is used to store each line of replace 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 prompts for compression with command line as a separate positional parameteroptions. In You could do this case the sed command is used by adding a third argument and requiring it to convert spaces to plus signs include a compression type, or by creating a mutually exclusive group with three arguments in it (+one for each compression type), which will be converted back later. Finally, a Neither of these is more '''forcorrect''' loop is used than the other. Pick which one you would like to create each account ('''useradd''') try and mail finish the user their account information ('''mail''')script with it. Add the following code:</li></ol><brli><code style="color:#3366CC;font-family:courier;font-size:.9em;font-weight:bold;"><br>When you are finished, you should be able to specify the directory to archive, the name of the archive to create, and the compression type (if [ ! -f $inputFile ]<br>then<br>&nbsp; echo "The file pathname \"$inputFile\" is empty or does not exist" >&2<br>&nbsp; exit 2<br>fi<br><br>set $(sed 's/ /+/g' $inputFileany) from the command line. # temporarily convert spaces to + The user should no longer be prompted for storing lines as positional parametersanything after hitting <br><br>for x<br>do<brcode>&nbsplt; enter&nbspgt; userPassWd=$(date | md5sum | cut -d" " -f1)<br>&nbsp; &nbsp; useradd -m -c "$(echo $x | cut -d":" -f2 | sed 's/+/ /g')" -p $userPassWd $(echo $x | cut -d":" -f1)<brcode>&nbsp; &nbsp; mail -s "Server Account Information" $(echo $x | cut -d":" -f3) <<+<br>&nbsp; &nbsp; Here is your server account information:<br>&nbsp; &nbsp; servername: myserver.senecac.on.ca<br>&nbsp; &nbsp; username: $(echo $x | cut -d":" -f1)<br>&nbsp; &nbsp; password: $userPassWd<br>&nbsp; &nbsp; Regards,<br>&nbsp; &nbsp; IT Department<br>+<br>done<br><br>echo -e "\n\nAccounts have been created\n\n"<br>exit 0<br/li></codeol>
<ol><li value="16">Save, set permissions, and then run that shell script for the input text file '''user-data.txt'''. Did it work? Try running the script without an argument - What did it do? </li><li>You have completed lab4. Proceed to Completing The Lab, and follow the instructions for "lab sign-off".</li></ol>
'''Answer INVESTIGATION 4 observations / questions in your lab log book.'''
932
edits

Navigation menu