Difference between revisions of "OPS235 Lab 4 - CentOS7"

From CDOT Wiki
Jump to: navigation, search
 
(27 intermediate revisions by 2 users not shown)
Line 1: Line 1:
 
[[Category:OPS235]]
 
[[Category:OPS235]]
 
+
{{Admon/caution|THIS IS AN OLD VERSION OF THE LAB|'''This is an archived version. Do not use this in your OPS235 course.'''}}
 
=LAB PREPARATION=
 
=LAB PREPARATION=
==Purpose / Objectives of Lab 1==
 
[[Image:hostmachine.png|thumb|right|300px|The c7host Linux server will run virtualization software to install and run 3 virtual machines (installed in lab2). ]]
 
You need to install a Linux OS to be a host or "platform" to install and use other Linux VMs (Virtual Machines) during this course.
 
  
The Linux OS you will be installing in this lab will be a Host Machine (''hostname'': '''c7host''') that will allow you to run '''Virtualization Software''' to create 3 separate virtual machines (to be performed in lab2). It is important to install this host machine correctly since other labs will depend on the stability of this host machine.
+
==Purpose / Objectives of Lab 4==
 +
{| width="40%" align="right" cellpadding="10"
 +
|- valign="top"
 +
|
 +
[[Image:users.png|thumb|right|150px|System administrators are required to add, remove and modify user accounts.]]
 +
|
 +
[[Image:on-off.png|thumb|right|135px|In order to perform maintenance, system administrators need to know how to stop and start services for a Linux system. ]]
 +
|}
  
  
<u>Main objectives</u>:
+
There are many other tasks that a Linux system administrator must perform other than installing Linux and installing software.
<br>
 
:* '''Correctly install the CentOS 7 FULL INSTALL DVD''' (not LIVE DVD) on your removable hard disk.
 
  
:* '''Record installation characteristics of CentOS 7 FULL INSTALL''' in a chart (contained in lab2 logbook chart) to compare with other installation methods performed in lab2.
+
A few additional tasks are user management and managing services.
  
:* '''Verify correct settings''' prior to proceeding with host installation stages.
 
  
:* '''Obtain Linux server information after installation''' to create a software asset report for later access.
+
<u>Main Objectives</u>:
 +
<br>
 +
:* Administer '''(add, remove, modify) users''' on a Linux system.
 +
:* Save time while adding new users using a template of '''start-up files'''.
 +
:* Create and manage '''groups''' on a Linux system.
 +
:* '''Start and Stop services''' on a Linux system.
 +
:* Display the '''status of running services''' on a Linux system.
  
:* '''Disable Linux Kernel security enhancements''' to allow easier internal networking connections (to be reactivated in a later lab).
 
  
:* Observe that '''Bash Shell Scripts can automate routine tasks'''.
 
  
 +
==Minimum Required Materials==
  
==Minimum Required Materials==
+
{|cellpadding="15" width="40%"
{|
 
  
 
|- valign="top"
 
|- valign="top"
  
| [[Image:blank-cd.png|thumb|left|75px|<b>CentOS 7</b>FULL INSTALL DVD]]
+
|width="10%" | [[Image:harddrive.png|thumb|left|85px|<b>Removable Hard Disk Pack</b> (SATA)]]
 
 
| [[Image:harddrive.png|thumb|left|75px|<b>Removable Hard Disk Pack</b> (SATA)]]
 
  
| [[Image:ubs-key.png|thumb|left|75px|<b>USB key</b><br>(for backups)]]
+
|width="10%" |[[Image:ubs-key.png|thumb|left|85px|<b>USB key</b><br>(for backups)]]
  
| [[Image:log-book.png|thumb|left|60px|<b>Lab Log Book</b><br>(labs 1 & 2)]]
+
|width="10%" |[[Image:log-book.png|thumb|left|70px|<b>Lab4 Log Book</b>]]
  
| width="40%" |{{Admon/tip|Access to Instructions for Lab1|Since you will performing a full install on your computer, you cannot use that computer to simultaneously view instructions while you perform the full install. Here are some suggestions to make this process easier:<ul>  <li>'''Printout Lab1 instructions''' at home prior to performing Lab1</li>  <li>'''Use a smart-phone, notebook, or netbook computer to view lab instructions''' (highly recommended)</li><li>If lab space availability is not an issue, '''use another computer termimal to view lab instructions''' while performing install</li><li>'''Follow step-by-step instructions from your OPS235 instructor''' (if demonstrated by instructor)</li></ul>|
 
}}
 
 
|}
 
|}
 
  
 
==My Toolkit (CLI Reference)==
 
==My Toolkit (CLI Reference)==
  
{| width="100%"
+
{|width="50%" cellpadding="15"
 
|- valign="top"
 
|- valign="top"
|<u>Package Management</u>
+
|width="10%" |<u>User Management:</u>
[http://www.rpm.org/max-rpm/rpm.8.html rpm]<br>
+
[http://unixhelp.ed.ac.uk/CGI/man-cgi?useradd+8 useradd]<br>
[http://man7.org/linux/man-pages/man8/yum.8.html yum]
+
[http://unixhelp.ed.ac.uk/CGI/man-cgi?userdel+8 userdel]<br>
|<u>System Information</u>
+
[http://unixhelp.ed.ac.uk/CGI/man-cgi?usermod+8 usermod]<br>
 +
[http://unixhelp.ed.ac.uk/CGI/man-cgi?groupadd+8 groupadd]<br>
 +
[http://unixhelp.ed.ac.uk/CGI/man-cgi?groupdel+8 groupdel]
 +
|width="10%" |<u>Managing Services</u>
 +
[http://unixhelp.ed.ac.uk/CGI/man-cgi?chkconfig+8 chkconfig]<br>
 +
[http://unixhelp.ed.ac.uk/CGI/man-cgi?service+8 service]<br>
 +
[http://www.dsm.fordham.edu/cgi-bin/man-cgi.pl?topic=systemctl systemctl]<br>
 +
|width="10%" |<u>Miscellaneous</u>
 +
[http://man7.org/linux/man-pages/man5/passwd.5.html /etc/passwd]<br>
 +
[http://man7.org/linux/man-pages/man5/group.5.html /etc/group]<br>
 +
[http://man7.org/linux/man-pages/man5/shadow.5.html /etc/shadow]<br>
 +
[http://archive.linuxfromscratch.org/blfs-museum/1.0/BLFS-1.0/postlfs/skel.html /etc/skel]<br>
 +
[http://zenit.senecac.on.ca/wiki/index.php/Init_vs_systemd init vs systemd]
 +
|}
 +
 
 +
 
 +
= INVESTIGATION 1: User/Group Management =
  
[http://man7.org/linux/man-pages/man1/hostname.1.html hostname]<br>
+
User account management is a very important operation that a Linux sysadmin does on a consistent basis. The sysadmin not only needs to add or remove user accounts by issuing commands, but may need to automate user account creations a large number (batch) of potential employees. There are many features with the Linux command to create new users including: specification of a home directory, type of shell used, name, password and time-limit (referred to as "aging") for a new user account. Remove user accounts also have options such as removing the user account but keeping the home directory for reference or evidence of "wrong-doing"
[http://man7.org/linux/man-pages/man1/uname.1.html uname]<br>
 
[http://man7.org/linux/man-pages/man1/ps.1.html ps]<br>
 
[http://man7.org/linux/man-pages/man8/lsblk.8.html lsblk]<br>
 
|<u>Networking</u>
 
  
[http://man7.org/linux/man-pages/man8/ifconfig.8.html ifconfig]<br>
+
In your ULI101 course, you learned to change permissions for directories and files relating to user, same group members and other group members. In this course, since you are the sysadmin with root privileges, you can create or remove groups as well as change the ownership of directories and files! We will now learn to perform key user account management operations in this section.
[http://man7.org/linux/man-pages/man8/netstat.8.html netstat]<br>
 
[http://man7.org/linux/man-pages/man8/route.8.html route]<br>
 
[http://linux.die.net/man/1/nslookup nslookup]<br>
 
|<u>Miscellaneous</u>
 
  
[http://unixhelp.ed.ac.uk/CGI/man-cgi?grep grep]<br>
+
== Part 1: The /etc/passwd file ==
[http://man7.org/linux/man-pages/man1/wc.1.html wc]<br>
 
[http://man7.org/linux/man-pages/man1/pwd.1.html pwd]<br>
 
[http://man7.org/linux/man-pages/man1/ls.1.html ls]<br>
 
[http://man7.org/linux/man-pages/man1/more.1.html more]<br>
 
[http://man7.org/linux/man-pages/man1/file.1.html file]<br>
 
[http://man7.org/linux/man-pages/man1/wget.1.html wget]<br>
 
[http://man7.org/linux/man-pages/man1/chmod.1.html chmod]<br>
 
[http://man7.org/linux/man-pages/man1/scp.1.html scp]<br>
 
[http://ss64.com/vi.html vi]
 
  
|width="40%"|{{Admon/tip|Online Hands-on Linux Tutorials (recommended)|The following online tutorial will allow you to practice Linux commands that you learned from ULI101 as well as essential shell scripting skills. Login to your '''Matrix''' account, and issue the pathnames to run the online tutorial in Matrix:<br><ul><li>Using the vi Text Editor:<br>'''/home/murray.saul/vi-tutorial'''<br><li>Linux Basics:<br>'''/home/murray.saul/linux-basics'''</li><li>Shell Scripting - Part I (Scripting Basics):<br>'''/home/murray.saul/scripting-1'''</li></ul>|
+
# Look at the <b><code><span style="color:#3366CC;font-size:1.2em;">/etc/passwd</span></code></b> file.
}}
+
# Make note of the contents of that file.
|}
+
# Read about the file: http://man7.org/linux/man-pages/man5/passwd.5.html
 +
# Make sure you know what information each field contains.
 +
# Why do you think there are so many users?
 +
# Look at the names of the users. What do you think these user names represent? Are they people?
 +
# What is the numeric user ID (UID) of the root user?
 +
# The user IDs of real users (people) are different from the user IDs of system accounts. What is the pattern?
  
=INVESTIGATION 1: CREATE HOST MACHINE (c7host)=
+
'''Answer the Part 1 observations / questions in your lab log book.'''
  
For the next 3 investigations, you will learn how to install your Centos Full DVD onto your removable hard disk. You will customize your install to setup several separate partitions:<ul><li>'''/''' (The "root" partition)</li><li>'''/home''' (Store regular user accounts)</li><li>'''/var/lib/libvirt/images''' (store virtual machine images to be created in lab2)</li><li>'''swap'''  partition (Virtual Memory)</li></ul>
+
== Part 2: Adding users ==
  
Make certain to record your observations of this install in the comparison chart for '''c7host''' in your lab2 logbook.
 
  
==Part 1: Start Installation ==
+
#Perform this part in your '''centos1''' VM.
 +
# Read the man page for the <b><code><span style="color:#3366CC;font-size:1.2em;">useradd</span></code></b> command.
 +
# Create three fictitious users (make-up their userids and full names. Give each of these newly-created users a password.
 +
# Grep the <b><code><span style="color:#3366CC;font-size:1.2em;">/etc/passwd</span></code></b> file for each of the new users.
 +
#* What is the '''home''' directory of each user?
 +
#* What '''group''' is each user in?
 +
#* What other information can you provide regarding these users?
 +
#* Where are the '''passwords''' stored?
 +
# Look at the man page for '''/etc/shadow''' using the command: <b><code><span style="color:#3366CC;font-size:1.2em;">man 5 shadow</span></code></b>
 +
#* Grep the <b><code><span style="color:#3366CC;font-size:1.2em;">/etc/shadow</span></code></b> file for each of the new users.
 +
#* Make note of this information.
 +
# Create two new dummy users, <b><code><span style="color:#3366CC;font-size:1.2em;">ops235_1</span></code></b> and <b><code><span style="color:#3366CC;font-size:1.2em;">ops235_2</span></code></b>.
 +
# Investigate the home directory of one of your new users.
 +
#* What files are there? Be sure to include hidden files.
 +
#* What do you think these files are used for?
 +
#* How does the operating system determine which files are created in a new home account? The answer can be found here:<br>http://www.linuxhowtos.org/Tips%20and%20Tricks/using_skel.htm
 +
#* Look at the files (including hidden files) in the template directory referred to in the article. Compare them to what is in a home directory for a new user. What do you notice?
 +
#* Create a new file in this directory with the following command: <b><code><span style="color:#3366CC;font-size:1.2em;">touch foo</span></code></b>
 +
#* Create a new user named <b><code><span style="color:#3366CC;font-size:1.2em;">foobar</span></code></b>, with the option to automatically create a home directory.
 +
#* Look at the contents of foobar's home directory. What do you notice?
 +
# Be sure to record your observations in your lab notes.
 +
#Issue the man pages for the '''useradd''' command. Explain the purpose of using the '''-e''' option for the ''useradd'' command. Try to think what would be the purpose for a Linux sysadmin to use this option when creating new users.
  
 +
'''Answer the Part 2 observations / questions in your lab log book.'''
  
 +
== Part 3: Managing Groups ==
  
::'''<u>Host Machine Details:</u>'''
+
#Remain in your '''centos1''' VM for this section.
 +
# Read the man page for the <b><code><span style="color:#3366CC;font-size:1.2em;">groupadd</span></code></b> and <b><code><span style="color:#3366CC;font-size:1.2em;">groupdel</span></code></b> commands.
 +
# Note which option allows you to set the Group ID number ('''GID''') when you create a new group.
 +
# Examine the file <b><code><span style="color:#3366CC;font-size:1.2em;">/etc/group</span></code></b>
 +
#* Which values of GID are reserved for system accounts?
 +
#* Which values of GID are reserved for non-system user accounts?
 +
#* What is the lowest available GID number for non-system users?
 +
#* What is the default group name of a new user?
 +
#* Add a new group named <b><code><span style="color:#3366CC;font-size:1.2em;">ops235</span></code></b> with a GID of <b><code><span style="color:#3366CC;font-size:1.2em;">600</span></code></b>.
 +
#* The management at your organization have concerns regarding some irresponsible users on your system.
 +
#** Add a new group named '''investigation'''.
 +
#** Look at '''/etc/group''' and note the GID of group called '''investigation'''.
 +
#** What GID is given to a new group if you do not specify it?
 +
#** In the file, add those users to the end of the concerned group (separate each user-name with a comma).
 +
#** Those individuals have explained their actions to management and the crisis has been resolved. Delete the '''investigation''' group.
 +
#** Look at '''/etc/group''' again and note the change.
  
::*'''Name:''' c7host
+
'''Answer the Part 3 observations / questions in your lab log book.'''
::*'''Boot media / Installation:''' CentOS7 Full Install DVD
 
::*'''Memory:''' 8GB
 
::*'''Disk space:''' 250GB (or higher)
 
::*'''CPUs:''' 1
 
  
{| width="40%" align="right" cellpadding="10"
+
== Part 4: Deleting / Modifying Users ==
|- valign="top"
 
|colspan="2"|{{Admon/important |You're supposed to use this hard drive only for this course| But if you really need to use it for two courses, and the professor for the other (probably windows)  course will allow it - ask your professor for help with partitioning.}}
 
|- valign="top"
 
|
 
[[Image:lab2-logbook.png|thumb|right|100px|'''comparison chart''' in lab2 logbook.]]
 
|
 
[[Image:installation_summary.png|thumb|right|400px|The '''Installation Summary''' screen provides flexibly when configuring to install on your computer. ]]
 
|}
 
  
# Refer to this listing of installation screenshots if you need a reference:<br>[ [http://matrix.senecac.on.ca/~murray.saul/ops235/installation/ installation screenshots] ]<br>
+
#Remain in your '''centos1''' VM for this section.
# Insert your '''removable SATA hard disk''' into the drive tray.
+
# Read the man page for the '''userdel''' command. Note which option automatically removes the users home directory when that user is deleted.
# Set your computer's drive selector switch to '''external''' (a.k.a ''position #4'').
+
# Delete the user '''ops235_1''' using the command <b><code><span style="color:#3366CC;font-size:1.2em;">userdel ops235_1</span></code></b>
# Power up the computer and insert the '''CentOS 7 Installation DVD''' into the DVD drive, then power-off computer.
+
# Delete the user '''ops235'''_2 using the same command with the option which removes the home directory of the user.
# Determine if your computer is the <u>newer</u> or <u>older</u> model. '''Newer computer models''' are labelled '''HP Z230'''.<br><br>'''NOTE:''' If you are using the '''<u>newer</u>''' model, allow the computer to boot up (<u>without</u> pressing F10 key) to boot from DVD. For <u>'''older'''</u> models, press F10, press ENTER for password, and select the DVD drive. Refer to the comparison chart in lab2 lab logbook, and fill in various installation information for '''c7host''' while you perform the installation (such as time it took to perform a full install, installation options, etc).<br><br>'''WARNING:''' Only use the same type of computer (only the <u>'''newer'''</u> computer or only the <u>'''older'''</u> computer) when working in the Seneca labs for the duration of this course!<br><br>
+
# Check the contents of the /home directory. What do you notice?
<ol>
+
# Check the contents of the <b><code><span style="color:#3366CC;font-size:1.2em;">/etc/group</span></code></b> file. What do you notice?
<li value="6">Select the option '''Test this Media & Install Centos7'''. Your DVD will be checked for defects.</li>
+
# Read the man page for the usermod command. Note which options change the user's full name, primary group, supplementary groups, and shell.
<li>If the check is successful, you will be prompted for a language. In the first screen, select language '''English''' with subselection '''English-Canada''' and then click the '''Continue''' button on the bottom right-hand screen.</li>
+
# Create a new user account called '''noobie''' for the employee: '''"Really Green"''' . Assign a password for that newly created user.
 +
# Management has indicated that this employee be on on probation for 3 months. Use the '''usermod''' command to set the account for noobie to expire in 3 months from this day as part of the security policy of this organization.
 +
# Add each of your new users to the group ops235 (in other words, add ops235 to each user as a supplementary group).
 +
# Examine <b><code><span style="color:#3366CC;font-size:1.2em;">/etc/group</span></code></b>. What has changed?
 +
# Use the '''usermod''' command to change the full name of the user account '''noobie''' from '''"Really Green"''' to '''"Outstanding Employee"'''. Examine the result of running that command in the <b><code><span style="color:#3366CC;font-size:1.2em;">/etc/passwd</span></code></b> file. What has changed?
 +
# Use the '''usermod''' command to extend the use of their account for 5 years as of today.
 +
# Be sure to record your observations in your lab notes.
  
<li>The '''Install Summary''' should now appear. This screen allows the installer to customize their Centos7 system prior to installation.</li>
+
'''Answer the Part 4 observations / questions in your lab log book.'''
<li>Configure the following installation settings from the ''Install Summary Screen'':<br><br><b>DATE & TIME:</b><ul><li>Click on the Map to select Toronto area (you may also select from the drop-down menu section)</li><li>Click the <b>DONE</b> button at the top-left corner to finish and return to the Installation Summary screen.</li></ul><br><b>NETWORK & HOSTNAME:</b><ul><li>Select the default Ethernet connection and click the button on the top right-hand side to change the setting from <b>OFF</b> to <b>ON</b>.</li><li>At the bottom left-hand corner type the hostname: <b>c7host</b> (all lowercase letters)</li><li>Review your settings, then click the <b>DONE</b> button at the top-left corner to finish and return to the Installation Summary screen.</li></ul><br><b>SOFTWARE SELECTION:</b><ul><li>Select the software packages labelled: <b>Gnome Desktop</b></li><li>Click the <b>DONE</b> button at the top-left corner to finish and return to the Installation Summary screen.</li></ul><br></li> <li>Although the Centos installtion program can provide suggestions on how to partition your hard disk, you will be customizing partitions for your hard disk. This custom partitioning is important since it will have consequences on future labs that you perform (especially for lab2).<br><br>Proceed to '''Part 2''' to customize your partitions.</li>
 
</ol>
 
  
  
== Part 2: Custom Partitioning ==
+
=INVESTIGATION 2: Managing System Services and Run-levels=
  
{|width="40%" align="right" cellpadding="10"
+
Many students may think that the following topic is small and "not a big deal". Those students may say, '''"How hard is running and stopping services?"'''
|- valign="top"
 
|
 
{{Admon/tip|Mount Points and Linux File System Types|Similar to other Operating Systems like windows '''fat''' / '''vfat''' / '''ntfs''' file system types, it is good to know a few common file system types in Linux for comparison:<br><ul><li><b>xfs:</b> &nbsp; Newer filesystem (fast transfer rates for large files, Journaling)</li><li><b>ext4:</b> &nbsp; Newer filesystem supporting large files and Journaling (used in for this lab)</li><li><b>ext2:</b> &nbsp; Stable filesystem popular for databases (no journaling)</li></ul>|
 
}}
 
|-
 
|
 
[[Image:partition_verification.png|thumb|right|550px|Carefully verify partition mount-names and sizes prior to proceeding with install. Check [http://matrix.senecac.on.ca/~murray.saul/ops235/installation/ installation screenshots] link for verification.]]
 
|}
 
#From the installation summary screen, click '''Installation Destination'''.
 
#In the installation destination screen, select the destination option: '''I will configure partitioning''' and then click '''Done'''.
 
#The manual partitioning screen should appear.
 
#If you have used your hard disk for previous Linux (Centos) distributions, you should remove them. Click on the distribution, and for each partition, select the partition and click the remove button (minus sign) and confirm deletion.
 
#Change the option '''New mount points will use the following partition scheme''' from '''LVM''' to '''<u>Standard Partition</u>''' (you will not be using LVM for your c7host machine).
 
#Before you proceed with creating partitions, let's see the partitions that we need to create for our host computer:<ul><li>Primary Partitions (ext4):<ul><li>'''30GB''' for '''/'''  (i.e. "root")</li><li>'''40GB''' for /home</li><li>'''100GB''' for '''/var/lib/libvirt/images''' </li></ul> </li><li>Swap Partition:<ul><li>'''16GB''' (Note: "swap" must be selected from the drop down menu)</li></ul></li></ul><br>'''NOTE:''' Remember that the sizes are recorded in MB (eg. 30 GB = 30000 MB) and you should multiply GB by a factor of 1024 to get the correct size.<br> (eg. '''30 GB x 1024 = 30720 MB''')<br><br>
 
#We will now create the root (/) partition. '''Click on the add button (plus) sign'''.<br>
 
#In the '''Add a New Mount Point''' screen, select '''/''' as the mount-point (either by typing or selecting from drop-down menu), and enter '''30720''' in for partition size and click '''Add Mount Point''' button.
 
#Repeat the same steps above for the '''/home''' partition and '''/var/lib/libvirt/images''' partition. You need to type the ''/var/lib/libvirt/images'' partition since it does not appear in the drop-down menu.
 
#Select each of the created partitions, and make certain that the file-system type is changed from '''xfs''' to '''ext4'''.
 
#Finally, add a swap partition (Mount Point: swap) for '''16 GB'''.
 
#Check that your partition settings are correct (you can ask your instructor or lab monitor to confirm), and then click '''Done''' to proceed.
 
#A Summary of Changes screen will appear to show the partitioning operations that will be created. Click the '''Accept Changes''' and click '''Begin Installation''' in the Installation Summary screen to proceed with the installation.
 
#Start timing your host machine installation.
 
  
 +
The process may not be hard, but knowing how to stop, start, restart and check the status of services is absolutely critical to a Linux server. '''Aside from learning to trouble-shoot problems''' by checking the status of running services, '''understanding how to manage services is critical to help protect a Linux server from penetration''' (this term is referred to as "'''Hardening a system'''"). Sometimes it is "what we don't know" that can harm us. One key element in hardening a computer system is to disable non essential networkng services to allow IDSs ('''Intrusion Detection Systems''') to focus on a narrower range of policy violations. A Debian-based penetration testing distribution called '''Kali''' (formerly referred to as '''"BackTrax"''') allows sysadmins and security professionals to identify vulnerabilities in their computer systems, and thus improve (harden) their systems against penetration. Learning to monitor the status, enable and disable networking services underlies the '''Backtrax''' motto:<br><br>'''''"The quieter you are, then more you will hear..."'''''<br><br>
  
== Part 3: Completing the Installation ==
+
=== Part 1: How do we Manage System Services? ===
  
{|width="40%" align="right" cellpadding="10"
+
We have seen that maintaining unneeded '''packages can be a security risk''' due to the unnecessary increase in the complexity of your system. Similarly, it is also unnecessarily hazardous, and even more so, to leave unneeded services running. In this investigation, we will learn how to '''control services, and turn off those services that we think are not necessary to help reduce security risks'''.
|- valign="top"
 
|[[Image:completed.png|thumb|right|500px|This screen indicates that installation is complete. You should remove the install DVD and confirm Centos7 boots from your removable hard drive. ]]
 
|}
 
#During the installation process, you will required to create a '''root password''' (for administration access) and create a '''regular user account'''. Click on '''Root Password''' and enter your root password. Think of an appropriate password and record that password somewhere in case you forget! An indicator will appear to show you how secure your password is. Retype your root password and click '''Done''' (you may have to click Done <u>twice</u> if your password is not considered to be a strong password).
 
#You need to create a regular user account. This account will be used to graphical log into your host machine. It is never recommended to graphically log into a graphical Linux/Unix system as root. It is better to log into a regular user account, then run a command to login as root (you will learn how to do this later in this lab).
 
#Click '''User Creation''' and enter your '''full name''', '''username''', and an appropriate '''password''' (and confirm password). Click '''Done''' to finish (click twice if password is not considered to be a strong password).
 
#Remember to record this host installation information in the '''installation comparison chart''' in the lab2 logbook.
 
#When installation is complete, you will notice a message at the bottom of the screen stating: '''CentOS is now successfully installed and ready for you to use!'''
 
#Click the Reboot button. Your DVD will <u>briefly</u> open in the DVD drive bay. Make certain to remove this installation DVD so that Centos will boot from your hard drive.
 
#After the system reboots, a boot menu should briefly appear, then prompt the user to accept the License Information (what is the purpose of accepting the license?).
 
#Click on '''License Information''' and '''click that you agree to the license agreement''', click '''Done''' and then click '''Finish Configuration'''.
 
#Click Forward to enable Kdump (what is the purpose of this application?).
 
#The system should then graphically prompt the user to login with their regular user account. Click on your '''regular user account name''' and '''enter your regular user password'''.<br><br>
 
#The last phase of the installation process should now run:<ul><li>Confirm English as the default input source and click '''Next'''.</li><li>Skip the creation of online accounts by clicking '''Next'''.<li>Start using your installed Linux system by clicking '''Start Using CentOS Linux'''.</li></ul><br>
 
#Stop timing your installation and note the amount of time that your installation took to perform. Also take the time to fill in the c7host section of the installation comparison chart in your lab2 logbook.
 
#Open a web-browser and check to see if you can connect to the Internet.<br><br>
 
#Your system automatically enables a '''screen-saver''' application which is a useful security tool to prevent unauthorized viewing of information on a terminal after a certain amount of inactivity. If you find this feature annoying and want to turn it off or adjust the idle time perform the following steps:<ol type="a"><li>Click on your '''username at the top right-hand screen'''</li><li>Select '''Settings''' from the drop-down menu</li><li>Click the '''Power''' icon located in the ''Settings'' Dialog Box</li><li>Change the amount of time in the '''Power Saving''' section to '''Never''' or a '''longer period of time'''</li><li>Close the ''Settings'' Dialog box.<br><br></li></ol>
 
#Proceed to Investigation 2 to obtain basic information from your newly installed Centos Host machine.
 
  
'''Answer Investigation 1 observations (all parts and questions) in your lab log book.'''
+
#Use your '''centos2''' VM for this part.
 +
<ol>
 +
  <li value="2">Use the '''man''' pages to learn about the '''service''' command.</li><li>Issue the following Linux command:
 +
      <ul>
 +
        <li><b><code><span style="color:#3366CC;font-size:1.2em;">service --status-all</span></code></b></li>
 +
      </ul>
 +
  </li>
 +
  <li>Note the services that are currently running.</li>
 +
  <li>Use the command <b><code><span style="color:#3366CC;font-size:1.2em;">service iptables stop</span></code></b> to stop the service named '''iptables'''</li>
 +
  <li>Run a command to verify that the '''iptables''' service has stopped.<br><br>'''NOTE:''' Although the service command seems to work, it is <u>'''deprecated'''</u> (i.e. "out-dated:). It has been replaced by using the [http://zenit.senecac.on.ca/wiki/index.php/Init_vs_systemd#systemd_Command_Usage systemctl] command. This is a command based upon a newer method of starting and managing system services called [http://zenit.senecac.on.ca/wiki/index.php/Init_vs_systemd systemd] (which replaces init - the "initialization table"). This method allows services to run more independently of each other, so that a service may be stopped without other dependent services to be stopped as well.<br><br>The most common '''systemctl''' commands are shown below (it is optional to include the filename extension '''.service''' after the service-name):<ul><li><span style="font-family:courier;font-size:1.2em;font-weight:bold;">'''systemctl list-units --all'''</span> &nbsp; (get a listing of all service names. Can pipe to grep to list service you are interested in)</li><li><span style="font-family:courier;font-size:1.2em;font-weight:bold;">'''systemctl status service-name'''</span> &nbsp; (Confirm status of a service - running or not-running)</li><li><span style="font-family:courier;font-size:1.2em;font-weight:bold;">'''systemctl stop service-name'''</span> &nbsp; (stop a service)</li><li><span style="font-family:courier;font-size:1.2em;font-weight:bold;">'''systemctl start service-name'''</span> &nbsp; (start a service)</li><li><span style="font-family:courier;font-size:1.2em;font-weight:bold;">'''systemctl restart service-name'''</span> &nbsp; (restart a service)</li><li><span style="font-family:courier;font-size:1.2em;font-weight:bold;">'''systemctl enable service-name'''</span> &nbsp; (enable service so service runs upon system startup)</li><li><span style="font-family:courier;font-size:1.2em;font-weight:bold;">'''systemctl disable service-name'''</span> &nbsp; (disable service so it does NOT run upon system startup)<br><br></li></ul></li>
 +
  <li>If you reboot now - the iptables service will be turned back on. We don't want it on though, it causes students headaches.<br>To turn it off permanently we need to use the '''systemctl''' command:<b><code><span style="color:#3366CC;font-size:1.2em;">systemctl disable iptables</span></code></b><br>(the '''chkconfig''' command used to be the way to enble/disable services, but is now deprecated).</li>
 +
  <li>Use the '''systemctl''' command to verify that the '''iptables''' service is no longer running ('''hint:''' issue command, and pipe to grep "'''iptables'''").
 +
  <li>Reboot and confirm that it's no longer running.</li>
 +
</ol>
  
 +
'''Answer Part 1 observations / questions in your lab log book.'''
  
=INVESTIGATION 2: OBTAINING HOST MACHINE SYSTEM INFORMATION=
+
===Part 2: How do we Manage Runlevels?===
  
 +
Running servers in graphical mode will make your system most likely to be penetrated. The X-windows framework can be vulnerable to attacks when these servers are connected to the Internet. This is why when you install server versions of Linux, they work in text-based mode only. Desktop versions of Linux are then installed on workstations (working in graphical mode) that connect to the server (for security reasons).
  
==Part 1: Obtaining Package Management / Package Information==
+
The Linux sysadmin can also change the run-level (or state) of a graphical Linux server to run in text-based mode and run the graphical mode by issuing a command when graphic mode is required. The run-level term is now deprecated in Fedora, and will likely be deprecated in RHEL/CentOS at some point as well, but for now this is what the industry is using.
  
{|width="40%" align="right" cellpadding="10"
 
|- valign="top"
 
|
 
{{Admon/important|Accessing the Administration Account (root)| Many administrative tasks require the root administrative account. There are many ways to access this administration account:<ul><li>Login: '''root'''  (enter root password)</li><li>Switch User to root (without login):<ul><li>'''su''': Remains in regular user's directory, does not run root's startup script(s).</li><li>'''su -''' : Changes to root's home directory (/root) and runs root's start script(s).</li></ul></li></ul>}}
 
|}
 
Navigate through your Graphical CentOS system, '''locate and run a terminal program (in order to issue Linux commands). Issue and record the commands used and the output generated in each of the following steps:'''
 
  
#With older (ancient) versions of Linux, a user once may have been allowed to login to their graphical Linux system using '''root''' as their user-name and their root password. This has been determined to be a security risk and that option has been removed with many or all Linux operating systems.
 
#Therefore, from this point onwards, you will be logging into your regular user account instead and issuing a command to login as the ''root'' user.
 
#Refer to the Information box regarding how to access the admin account from the command line.
 
#Issue the command <b><code><span style="color:#3366CC;font-size:1.3em;">su </span></code></b> Issue the '''pwd''' and '''whoami''' commands to confirm your directory pathname. When finished logout of this account.
 
#Issue the command <b><code><span style="color:#3366CC;font-size:1.3em;">su - </span></code></b> Issue the '''pwd''' and '''whoami''' commands to confirm your directory pathname. What do you notice are the main differences between using '''su''' versus using '''su -''' ?
 
# An installation log file called  <b><code><span style="color:#3366CC;font-size:1.2em;">/var/log/anaconda/anaconda.packaging.log</span></code></b> has been created to record the installation of your c7host machine. This file is an ASCII file which can be viewed with the <b><code><span style="color:#3366CC;font-size:1.2em;">more</span></code></b> command.
 
# You can make use of this file to determine how many packages have been installed: complete the following command to count the number of packages that are labelled "Installing" in the installation log file:
 
:: <b><code><span style="color:#3366CC;font-size:1.2em;">grep -i installing /var/log/anaconda/anaconda.packaging.log | wc -l'''</span></code></b>
 
<ol>
 
<li value="8">Issue that command displayed above. Does it work? If not, what account do you think you should be in? When you get the command working record this important information regarding commands and the admin account in your lab logbook.</li>
 
<li>Using the <code>rpm</code> command: you can also use the following commands to list all the installed packages, and the total number of packages installed:</li>
 
</ol>
 
::<b><code><span style="color:#3366CC;font-size:1.2em;">rpm -q -a'''</span></code></b>
 
::<b><code><span style="color:#3366CC;font-size:1.2em;">rpm -q -a | wc -l'''</span></code></b>
 
::<b><code><span style="color:#3366CC;font-size:1.2em;">rpm -qa  | wc -l'''</span></code></b>
 
<ol>
 
<li value="10">The <code>'''-q'''</code> option means query, and the <code>'''-a'''</code> option means all (in other words, query all installed software packages). Did you get the same number of packages from the above two methods?</li>
 
<li>Some of the files on your system were installed with the software packages, and some were created by system activity (for example, by creating your Learn account and by logging in). If you know the package name (from the <code>install.log</code>), you can list all the files that were installed from the package by using the following command:</li>
 
</ol>
 
::<b><code><span style=" pointer-events:none;cursor:default;color:#3366CC;font-size:1.2em;">rpm -q -l gedit</span></code></b>
 
  
<ol><li value="12">Issue the following command to obtain the total number of files installed for gedit:<br><br></li></ol>
+
#Perform this part in both your '''centos2''' and '''centos3''' VMs.
::<b><code><span style=" pointer-events:none;cursor:default;color:#3366CC;font-size:1.2em;">rpm -ql gedit | wc -l</span></code></b>
 
 
<ol>
 
<ol>
<li value="13">Using what you learned in steps 3, 4, and 7, get a count of the total number of files installed by all of the software packages on your system.</li><li>How can you explain why this number is a lot larger than the total number of packages installed? Record your answer in your lab logbook.
+
  <li value="2">Issue the following Linux command:
 +
      <ul>
 +
        <li><b><code><span style="color:#3366CC;font-size:1.2em;">runlevel</span></code></b></li>
 +
      </ul>
 +
  </li>
 +
  <li>Note the difference in output between '''centos2''' and '''centos3'''.</li>
 +
  <li>You can use the '''init''' command to change the current run-level. See a list of runlevels [https://www.centos.org/docs/5/html/5.2/Installation_Guide/s2-init-boot-shutdown-rl.html here].</li><li> Use the '''man''' command to learn how to use the '''init''' command. Use this command to change the current run-level in '''centos2''' to '''3'''. What happened?</li>
 +
  <li>Issue the following Linux command:
 +
    <ul>
 +
      <li><b><code><span style="color:#3366CC;font-size:1.2em;">startx</span></code></b></li>
 +
    </ul>
 +
  </li>
 +
  <li>What happens?</li>
 +
  <li>Log-off your graphical system. You should return to your shell prompt.</li>
 +
  <li>Using systemd requires a different method of setting text mode and graphical mode. You can refer to this link for future reference:
 +
[http://fedoraproject.org/wiki/Systemd#How_do_I_change_the_runlevel.3F How to Change Run-Levels with Systemd]</li><li>Restart your centos2 machine, and make certain that it runs in '''graphical''' mode</li>
 +
  </li>Why would you want to make a graphical Linux system run in text-based mode?</li>
 
</ol>
 
</ol>
  
  
==Part2: Obtaining System Information==
+
'''Answer Part 2 observations / questions in your lab log book.'''
 
 
{|width="40%" align="right" cellpadding="10"
 
|- valign="top"
 
|
 
{{Admon/important|Pathname for USB Stick|The default mount location has been changed in linux distributions newer than CentOS. So while we will get '''/media/usb-device-name''', in newer distributions you'll see '''/run/media/userloginid/usb-device-name'''}}
 
|}
 
#To find out the name that you have assigned to your Linux system, enter the command:  <b><code><span style="color:#3366CC;font-size:1.2em;">hostname</span></code></b>
 
#To find out the kernel version of your GNU/Linux workstation and the date it was created, enter the command:<br><b><code><span style="color:#3366CC;font-size:1.2em;">uname -rv</span></code></b>
 
#To find out all the system processes running on your GNU/Linux workstation, enter the command: <b><code><span style="color:#3366CC;font-size:1.2em;">ps -ef</span></code></b>
 
#We will now collect networking information for your installed system.
 
#To check the network configuration settings obtained from the DHCP server, run the following commands, describing the output in your log book:
 
::: <b><code><span  style="pointer-events: none;cursor: default;color:#3366CC;font-size:1.2em;">ifconfig</span></code></b>
 
::: <b><code><span  style="pointer-events: none;cursor: default;color:#3366CC;font-size:1.2em;">route -n</span></code></b>
 
:::<b><code><span  style="pointer-events: none;cursor: default;color:#3366CC;font-size:1.2em;">nslookup</span></code></b> (at the ''nslookup'' prompt, enter the word '''server''' and record the output. Type exit to leave nslookup).
 
<ol><li value="8">Find the following information in the output of the above commands:</li></ol>
 
::: <b><code><span  style="pointer-events: none;cursor: default;color:#3366CC;font-size:1.2em;">MAC address</span></code></b> of the ethernet network interface
 
:::<b><code><span  style="pointer-events: none;cursor: default;color:#3366CC;font-size:1.2em;">Subnet mask</span></code></b>
 
::: <b><code><span  style="pointer-events: none;cursor: default;color:#3366CC;font-size:1.2em;">The IP address </span></code></b> (assigned to you by the DHCP server)
 
::: <b><code><span  style="pointer-events: none;cursor: default;color:#3366CC;font-size:1.2em;">The default gateway</span></code></b>
 
::: <b><code><span  style="pointer-events: none;cursor: default;color:#3366CC;font-size:1.2em;">The DNS nameserver</span></code></b>
 
<ol><li value="9">Run the commands <b><code><span style="color:#3366CC;font-size:1.2em;">hostname</span></code></b>, <b><code><span style="color:#3366CC;font-size:1.2em;">uname -rv</span></code></b>, <b><code><span style="color:#3366CC;font-size:1.2em;">ps -ef</span></code></b>, <b><code><span style="color:#3366CC;font-size:1.2em;">ifconfig</span></code></b>, and <b><code><span style="color:#3366CC;font-size:1.2em;">route -n</span></code></b> redirecting the output to add to a file in root's home directory called <b><code><span style="color:#3366CC;font-size:1.2em;">system.txt</span></code></b>.</li><li>Copy the installation log file <code>'''/var/log/anaconda/anaconda.packaging.log'''</code> and the file '''system.txt''' to a USB memory key, or '''scp''' to your matrix account as a backup.</li></ol>
 
 
 
 
 
'''Answer the Investigation 2 observations / questions in your lab log book.'''
 
  
  
 
= INVESTIGATION 3: LOOKING AHEAD =
 
= INVESTIGATION 3: LOOKING AHEAD =
  
==Part 1: Disable SELinux and Perform Software Updates==
+
==Automating Routine Tasks (Shell Scripting)==
 
 
 
{|width="40%" align="right" cellpadding="10"
 
{|width="40%" align="right" cellpadding="10"
 
|- valign="top"
 
|- valign="top"
 
|
 
|
{{Admon/important|SELinux|SELinux stands for '''Security-Enhanced Linux'''. It is a component that helps to better secure the system to protect against intrusion (hackers). SELinux is enabled upon the default install of CentOS. SELinux can be a good thing, if you take care of it and know how it works. For this course it is strongly recommended that you '''disable SELinux by default''' because we won't have the time to reconfigure it every time the labs make it necessary.}}
+
{{Admon/tip|Bash Shell Scripting Tips:|<br><ul><li>'''The case statement:'''<br><br>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). After action(s) are taken for a particular scenerio (or "case"), a break statement (''';;''') is used to "break-out" of the statement (and not perform other actions). A default case (*) is also used to catch exceptions.<br><br><u>'''Examples (try in shell script):'''</u><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><li>'''The getopts function:'''<br><br></li></ul>The getopts function allows the shell scripter to create scripts that accept options (like options for Linux commands). This provides the Linux administrator with scripts that provide more flexibility and versatility. A built-in function called '''getopts''' (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. 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 ''':)''' and '''\?)''' cases for error handling.<br><br>'''<u>Example of getopts</u>''' (try in script and run with options)<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 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>}}
 
|}
 
|}
# Disabling SELinux is quite simple, just edit the file '''/etc/selinux/config''' and set SELINUX to disabled.
 
# Add additional text regarding disabling SELinux.
 
#The CentOS software is updated frequently to add features, fix bugs, and upgrade security. Perform a system update to get the latest versions of the packages installed: Start the Firefox web browser, turn off popup window blocking (select '''Edit''', '''Preferences''', then select the '''Content''' tab and uncheck the box to '''Block Popups'''), then return to your web-browser, load a page, and when prompted, login to SeneNET.
 
#Make certain that you have at least 30 minutes available in your lab-time prior to performing a system update. Never abort a system update since it may damage your system files and render your host mahcine inoperable!
 
#Open a terminal and type <b><code><span style="color:#3366CC;font-size:1.2em;">su</span></code></b> to start a shell as root. Enter the command <b><code><span style=" pointer-events:none;cursor:default;color:#3366CC;font-size:1.2em;">yum update</span></code></b> This will download and install all of the packages that have been updated since the installation DVD image was created.  If you complete this command at Seneca it should run quite fast as Seneca College hosts a CentOS Repository mirror (a copy of all of the current CentOS packages, on a local web server).
 
  
 +
We will now use shell scripting to help automate the task for a Linux adminstrator to create regular user accounts.
  
==Part 2: Automating Routine Tasks (Shell Scripting)==
 
  
{|width="40%" align="right" cellpadding="10"
+
#You will be using your '''c7host''' machine for this section.
|- valign="top"
+
#Download, study, and run the following shell script. Issue the command:<br><b><code><span style=" pointer-events:none;cursor:default;color:#3366CC;font-size:1.2em;">wget https://scs.senecac.on.ca/~murray.saul/user-create.bash</span></code></b>
|
+
#Try to understand what these Bash Shell scripts do, and then run the script as root. After running the shell script, view the contents of the '''/home''' directory to confirm.
{{Admon/tip|Bash Shell Scripting Tips:|<br><ul><li>'''She-bang line: #!/bin/bash'''<br><br>Shell scripts have evolved of the past 40 years. To avoid running a newer shell script on an older shell, it is recommended to force running the shell script in the correct shell. In order to do this, on the first line at the very beginning of the shell script, you add the '''#!''' ('''# as in "shhhh" - a comment''', and''' ! is referred to as "bang" run a commmand''': in this case, '''run the command: /bin/bash'''). You can issue the Linux command '''which bash''' to get the correct location. If there is no bash shell on that machine, the shell script will not run (as a precaution - the Linux admin will know how to make a fix to the shell script if required)<br>. </li><li>'''Variables:'''<br><br> There are 3 types of variables that can be used in shell scripting: '''ENVIRONMENT''' (eg. $USER), '''user-defined''' ($varName), and '''positional parameters''' (eg. $1, $2... containing arguments after shell script or by using set command (eg. '''set $(ls)''' ). Using dollar sign ('''$''') in front of variable expands the value assigned.<br><br></li><li>'''Command Substitution:'''<br><br>A very useful trick to take output from a command to be used as an argument for another command. Examples include:<br>'''file $(ls)'''<br>'''set $(ls);echo $#;echo $*'''<br>'''echo "hostname: $(hostname)"'''<br><br><li>'''Logic Control Flow Statements:'''<br><br>The '''test''' command can be used to see if a condition is true or false<br>(i.e. test $USER &#61; "root") . The '''$?''' special shell variable stores the result (zero if true, non-zero if false). Square brackets '''[ ]''' can be used to represent the test command with the condition <u>inside</u> the brackets (spaces separating brackets).Can use '''if''' / '''if-else''' / '''if-elif-else''' statements with brackets. The '''exit''' command can be used to terminate the shell script with a false value.<br><br>'''<u>Examples</u>'''<br><br>''if [ $USER &#61; "root" ]''<br>''then''<br>&nbsp;''echo "You must be root" >&amp;2''<br>&nbsp;''exit1''<br>''fi''<br><br># For number comparison: use:<br># -gt,-ge, -lt, -le, -eq, -ne<br><br>''if [ $age -gt 65 ]''<br>''then''<br>&nbsp;''echo "retire"''<br>''else''<br>&nbsp;''echo "don't retire"''<br>''fi''<br><br>''if [ $grade -gt 79 ]''<br>''then''<br>&nbsp;''echo "You get Good Mark"''<br>''elif [ $grade -gt 49 ]''<br>''then''<br>&nbsp;''echo "You pass"''<br>''else''<br>&nbsp;''echo "You fail"''<br>''fi''<br></li></ul>}}
 
|}
 
You may have learned about creating and running Bash Shell Scripts in your ULI101 course. Shell scripts help Linux users and system administrators to automate repetitive tasks to become more efficient and to help them save time. You will be reviewing and building a basic Bash Shell script to generate information reports for your newly-installed Linux host machine. Take time to view Shell Scripting Tips which are located on the right-hand side.
 
  
If you require <u>'''additional practice'''</u> in creating shell scripts and using the vi text editor, run the commands in your '''Matrix''' account: <ul><li>'''/home/murray.saul/vi-tutorial'''</li><li>'''/home/murray.saul/scripting-1'''</li></ul>
 
  
Perform the following steps in your '''c7host''' machine:
+
Although the '''zenity''' command is a "user-friendly" way to run shell scripts, Linux administrators usually create shell scripts that resemble common Linux commands. In 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 (including the use of options). Refer to the notes section on the right-hand-side for reference about the '''case''' statement and the '''getopts''' function.
  
# Make certain to log out of your root account and remain as a regular user.
 
# Open a Shell terminal and use a text editor (such as <b><code><span style="color:#3366CC;font-size:1.2em;">vi</span></code></b> or <b><code><span style="color:#3366CC;font-size:1.2em;">nano</span></code></b>) to create a Bash Shell script called: <b><code><span style="color:#3366CC;font-size:1.2em;">myreport.bash</span></code></b> in your current directory.
 
# Copy and paste the text below into your vi editing session for your file report.bash<br> (how do you copy and paste efficiently in Linux?)<br>
 
  
 +
<ol><li value="3">Open a Bash shell terminal and login as root.</li><li>Use the wget command to download the input file called user-data.txt by issuing the command:<br><b><code><span style="color:#3366CC;font-size:1.2em;">wget https://scs.senecac.on.ca/~murray.saul/user-data.txt</span></code></b></li><li>View the contents on the user-data.txt file to confirm there are 3 fields (username, fullname, and e-mail address)which are separated by the colon (:) symbol.<li><li>Use a text editor (such as <b><code><span style="color:#3366CC;font-size:1.2em;">vi</span></code></b> or <b><code><span style="color:#3366CC;font-size:1.2em;">nano</span></code></b>) to create a Bash Shell script called: <b><code><span style="color:#3366CC;font-size:1.2em;">createUsers.bash</span></code></b> in /root's home directory.</li><li>Enter the following text content into your text-editing session:</li></ol>
 
<code style="color:#3366CC;font-family:courier;font-size:.9em;margin-left:20px;">
 
<code style="color:#3366CC;font-family:courier;font-size:.9em;margin-left:20px;">
 
<br>
 
<br>
&#35;!/bin/bash<br>
+
&#35;!/bin/bash <br>
 
<br>
 
<br>
 +
&#35; createUsers.bash<br>
 +
&#35; Purpose: Generates a batch of user accounts (user data stored in a text file)<br>
 +
&#35;<br>&#35; USAGE: /root/createUsers.bash [-i {input-path}] <br>
 +
&#35;<br>
 
&#35; Author: *** INSERT YOUR NAME ***<br>
 
&#35; Author: *** INSERT YOUR NAME ***<br>
 
&#35; Date:  *** CURRENT DATE ***<br>
 
&#35; Date:  *** CURRENT DATE ***<br>
&#35;<br>
 
&#35; Purpose: Creates system info report<br>
 
&#35;<br>&#35; USAGE: ./myreport.bash<br>
 
 
<br>
 
<br>
if [ $USER != "root" ]  # only runs if logged in as root<br>
+
if [ $PWD != "/root" ]  # only runs if in root's home directory<br>
then<br>&nbsp;echo "You must be logged in as root." >&2<br>
+
then<br>&nbsp;echo "You must be in root's home directory." >&2<br>
 
&nbsp;exit 1<br>
 
&nbsp;exit 1<br>
 +
fi<br>
 +
if [ "$#" -eq 0 ] #  if no arguments after command<br>
 +
then<br>
 +
&nbsp;echo "You must enter an argument" >&2<br>
 +
&nbsp;echo "USAGE: $0 [-i {input-path}]" >&2<br>
 +
&nbsp;exit 2<br>
 
fi<br>
 
fi<br>
 
</code>
 
</code>
 
<br>
 
<br>
<ol><li value="4">Save your editing session, assign the '''myreport.bash''' file read and execute permissions (at least for the owner) and run by typing:<br><b><code><span style="color:#3366CC;font-size:1.2em;">./myreport.bash</span></code></b></li><li>Did it run? If not what do you think you need to do in order to run the Bash Shell Script?</li><li>Issue the command <b><code><span style="color:#3366CC;font-size:1.2em;">su -</span></code></b> and run the script from the regular user's home directory (not root's home directory):<br><b><code><span style="color:#3366CC;font-size:1.2em;">~regularuserid/myreport.bash</span></code></b></li><li> Did it work?</li><li>Reopen your text-editing session for '''~regularuserid/myreport.bash''' and add the following lines of code to the bottom of the shell script file:</ol>
+
<ol><li value="6">Save your editing session, but remain in the text editor.</li><li>The code displayed below uses the getopt function set the input file pathname or check for invalid options or missing option text. Add the following code</li></ol>
 
<br>
 
<br>
 
<code style="color:#3366CC;font-family:courier;font-size:.9em;">
 
<code style="color:#3366CC;font-family:courier;font-size:.9em;">
&#35; Create report title<br>
 
 
<br>
 
<br>
echo "SYSTEM REPORT" > /root/report.txt<br>
+
outputFlag="n"<br>
echo "Date: $(date +'%A %B %d, %Y (%H:%M:%p)')" >> /root/report.txt<br>
+
while getopts i: name<br>
echo  >> /root/report.txt<br>
+
do<br>
 +
&nbsp;case $name in<br>
 +
&nbsp; &nbsp;i) inputFile=$OPTARG ;;<br>
 +
&nbsp; &nbsp;:) echo "Error: You need text after options requiring text"<br>
 +
&nbsp; &nbsp; &nbsp; &nbsp;exit 1 ;;<br>
 +
&nbsp; &nbsp;\?) echo "Error: Incorrect option"<br>
 +
&nbsp; &nbsp; &nbsp; &nbsp; exit 1 ;;<br>
 +
&nbsp;esac<br>
 +
done<br>
 
</code>
 
</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>
 +
&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' $inputFile)  # temporarily convert spaces to + for storing lines as positional parameters<br>
 
<br>
 
<br>
<ol><li value="8">Save and run the bash shell script. View the contents of the file called '''report.txt''' that was generated (I hope you are using the up arrow key to issue previously issued commands in order to save time!). Notice how the redirection symbol &gt; is used at the beginning of the report, and then the other redirection symbol &gt;&gt; is used to help "grow" the report with the other content.</li><li>The only remaining content of the report would be the system information. We can use a shell scripting trick called "command substitution" $( .. ) in order place results from an command to be used by another command (like echo). Re-edit the shell script and add the following code at the bottom of the shell script file:</li></ol>
+
for x<br>
 +
do<br>
 +
&nbsp; &nbsp; 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)<br>
 +
&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>
 
<br>
<code style="color:#3366CC;font-family:courier;font-size:.9em;">
+
echo -e "\n\nAccounts have been created\n\n"<br>
echo  >> /root/report.txt<br>
+
exit 0<br>
echo "Hostname: $(hostname)"  >> /root/report.txt<br>
 
echo  >> /root/report.txt<br>
 
echo "Kernel Version: $(uname -rv)"  >> /root/report.txt<br>
 
echo  >> /root/report.txt<br>
 
 
</code>
 
</code>
<br>
 
<ol><li value="10">Save, run the script, and view the ''report.txt'' contents (are you using tip that was given to save time?).</li><li>Edit the shell script and include output from the <b><code><span style="color:#3366CC;font-size:1.2em;">ps aux</span></code></b> and <b><code><span style="color:#3366CC;font-size:1.2em;">ifconfig</span></code></b> commands (with appropriate titles). Remember to redirect that output to add to the bottom of the file!</li><li>Save, run and confirm that the shell script is working correctly.</li><li>What would be the use of keeping this shell script as a Linux system administrator?</li></ol>
 
<ol><li value="14">Here are some more "complex" Bash Shell scripts, that perform the same task. Although you are not require to understand some of these other tricks, it is recommended that you view the contents of the scripts and save them for future consideration or exmaples.</li><li>The <b><code>wget</code></b> command can be used to quickly download files from the Internet. Issue the following command:<br><b><code><span  style="pointer-events: none;cursor: default;color:#3366CC;font-size:1.2em;">wget https://scs.senecac.on.ca/~murray.saul/text-report.bash</span></code></b></li><li>Verify that the file '''text-report.bash''' was downloaded to your current directory.</li><li>Assign read and execute permissions for this file by issuing the command: <b><code><span style="color:#3366CC;font-size:1.2em;">chmod u+rx text-report.bash</span></code></b></li><li>Run this Bash Shell script by issuing the command: <b><code><span style="color:#3366CC;font-size:1.2em;">./text-report.bash</span></code></b></li><li>Check to see if it created a report in your current directory. What is the purpose of the report?</li><li>Use the <b>vi</b> text editor to view the contents of the file <b>text-report.bash</b>. Can you understand how this script works?<br><br></li><li>Use the <b><code>wget</code></b> command to download, study, and run the following shell scripts on-line:<blockquote><b><code><span style=" pointer-events:none;cursor:default;color:#3366CC;font-size:1.2em;">https://scs.senecac.on.ca/~murray.saul/report.bash<br>https://scs.senecac.on.ca/~murray.saul/report3.bash</span></code></b></blockquote></li><li>Try to understand what these Bash Shell scripts do.</li><li>You have completed lab1. Proceed to Completing The Lab, and follow the instructions for "lab sign-off".</li></ol>
 
  
 +
<ol>
 +
<li value="8">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 3 observations / questions in your lab log book.'''
  
'''Answer the Investigation 3 observations / questions in your lab log book.'''
+
= LAB 4 SIGN-OFF (SHOW INSTRUCTOR) =
 +
{{Admon/important|If you have successfully completed this lab, make a new backup of your virtual machines as well as your host machine.|}}
  
 +
'''Arrange proof of the following on the screen:'''
  
= LAB 1 SIGN-OFF (SHOW INSTRUCTOR) =
+
<ol><li><span style="color:green;font-size:1.5em;">&#x2713;</span> '''centos1''' VM:<blockquote><ul><li>Account created on '''centos1''' VM</li><li> List contents of '''/etc/group''' file (ops235 group)</li><li>List contents of '''/etc/passwd''' file (created accounts)</li></ul></blockquote><li><span style="color:green;font-size:1.5em;">&#x2713;</span> '''centos2''' VM:<blockquote><ul><li>Display current run-level status on '''centos2''' VM</li></ul></blockquote></li></li><li><span style="color:green;font-size:1.5em;">&#x2713;</span>'''c7host''' machine<blockquote><ul><li>Creation of your bash shell script called '''createUsers.bash'''</li></ul></blockquote></li><li><span style="color:green;font-size:1.5em;">&#x2713;</span> '''Lab4''' log-book filled out.</li></ol>
[[Image:lab1_signoff.png|thumb|right|500px|Students should be prepared with a'''ll required commands (system information) displayed in a terminal (or multiple terminals) prior to calling the instructor for signoff'''.]]
 
'''Arrange evidence (command output) for each of these items on your screen, then ask your instructor to review them and sign off on the lab's completion:'''
 
  
::<span style="color:green;font-size:1.5em;">&#x2713;</span> Output of '''lsblk''' command showing correct partition names and sizes
 
::<span style="color:green;font-size:1.5em;">&#x2713;</span> Contents of '''/etc/fstab''' file confirming partitions file types are '''ext4'''
 
::<span style="color:green;font-size:1.5em;">&#x2713;</span> Correct '''IP address''' and '''MAC address'''
 
::<span style="color:green;font-size:1.5em;">&#x2713;</span> '''Default route (gateway)'''
 
::<span style="color:green;font-size:1.5em;">&#x2713;</span> '''DNS name server IP Address'''
 
::<span style="color:green;font-size:1.5em;">&#x2713;</span> Contents of your '''report.bash''' shell script
 
::<span style="color:green;font-size:1.5em;">&#x2713;</span> proof of '''yum update''' performed on c7host
 
::<span style="color:green;font-size:1.5em;">&#x2713;</span> '''lab1 notes''' <u>and</u> '''first column of Comparison Chart in lab2'''.
 
  
= ADDITIONAL PRACTICE =
+
== Practice For Quizzes, Tests, Midterm &amp; Final Exam ==
  
# How many packages were installed?
+
# Describe all of the field in <code>'''/etc/passwd'''</code>
# How many files (correct to the nearest hundred) were installed?
+
# What is the command to create a user? What option to create a home directory for that user?
# How many users were created automatically on your system (regular, admin)?
+
# What is the command to change the full name of an already-created user?
# List 3 ways that you can access your root account
+
# What is the command to delete a user account? What option allows for the user's home directory to be removed as well?
# What is the difference between the commands '''su''' and '''su -''' ?
+
# What is the command to create a group? What is the command (or steps) to include a user in a newly-created group?
# What is the home directory for the user "root"?
+
# What is the purpose of <code>'''/etc/shadow'''</code>?
# How do you determine the host name of your GNU/Linux workstation?
+
# What is the purpose of <code>'''/etc/skel'''</code>?
# What command can display the NIC's MAC address?
+
# What does the term run-level mean?
# What command is used to get a list of running processes on your newly-installed system?
+
# How to set the run-level of a Linux system to text-based only? How to set to graphical mode?
# What is the command to copy files to your USB key?
+
# What is the command to view the status of running services?
# How can Shell Scripts be used to help automate a task performed in lab1?
+
# What is the command to start a service (like httpd, or sshd)?
 +
# What is the command to start a service?
 +
# Can a service be stopped and started by issuing just one command?
  
 
[[Category:OPS235]]
 
[[Category:OPS235]]
 
[[Category:OPS235 Labs]]
 
[[Category:OPS235 Labs]]

Latest revision as of 12:31, 24 September 2018

Stop (medium size).png
THIS IS AN OLD VERSION OF THE LAB
This is an archived version. Do not use this in your OPS235 course.

LAB PREPARATION

Purpose / Objectives of Lab 4

System administrators are required to add, remove and modify user accounts.
In order to perform maintenance, system administrators need to know how to stop and start services for a Linux system.


There are many other tasks that a Linux system administrator must perform other than installing Linux and installing software.

A few additional tasks are user management and managing services.


Main Objectives:

  • Administer (add, remove, modify) users on a Linux system.
  • Save time while adding new users using a template of start-up files.
  • Create and manage groups on a Linux system.
  • Start and Stop services on a Linux system.
  • Display the status of running services on a Linux system.


Minimum Required Materials

Removable Hard Disk Pack (SATA)
USB key
(for backups)
Lab4 Log Book

My Toolkit (CLI Reference)

User Management:

useradd
userdel
usermod
groupadd
groupdel

Managing Services

chkconfig
service
systemctl

Miscellaneous

/etc/passwd
/etc/group
/etc/shadow
/etc/skel
init vs systemd


INVESTIGATION 1: User/Group Management

User account management is a very important operation that a Linux sysadmin does on a consistent basis. The sysadmin not only needs to add or remove user accounts by issuing commands, but may need to automate user account creations a large number (batch) of potential employees. There are many features with the Linux command to create new users including: specification of a home directory, type of shell used, name, password and time-limit (referred to as "aging") for a new user account. Remove user accounts also have options such as removing the user account but keeping the home directory for reference or evidence of "wrong-doing"

In your ULI101 course, you learned to change permissions for directories and files relating to user, same group members and other group members. In this course, since you are the sysadmin with root privileges, you can create or remove groups as well as change the ownership of directories and files! We will now learn to perform key user account management operations in this section.

Part 1: The /etc/passwd file

  1. Look at the /etc/passwd file.
  2. Make note of the contents of that file.
  3. Read about the file: http://man7.org/linux/man-pages/man5/passwd.5.html
  4. Make sure you know what information each field contains.
  5. Why do you think there are so many users?
  6. Look at the names of the users. What do you think these user names represent? Are they people?
  7. What is the numeric user ID (UID) of the root user?
  8. The user IDs of real users (people) are different from the user IDs of system accounts. What is the pattern?

Answer the Part 1 observations / questions in your lab log book.

Part 2: Adding users

  1. Perform this part in your centos1 VM.
  2. Read the man page for the useradd command.
  3. Create three fictitious users (make-up their userids and full names. Give each of these newly-created users a password.
  4. Grep the /etc/passwd file for each of the new users.
    • What is the home directory of each user?
    • What group is each user in?
    • What other information can you provide regarding these users?
    • Where are the passwords stored?
  5. Look at the man page for /etc/shadow using the command: man 5 shadow
    • Grep the /etc/shadow file for each of the new users.
    • Make note of this information.
  6. Create two new dummy users, ops235_1 and ops235_2.
  7. Investigate the home directory of one of your new users.
    • What files are there? Be sure to include hidden files.
    • What do you think these files are used for?
    • How does the operating system determine which files are created in a new home account? The answer can be found here:
      http://www.linuxhowtos.org/Tips%20and%20Tricks/using_skel.htm
    • Look at the files (including hidden files) in the template directory referred to in the article. Compare them to what is in a home directory for a new user. What do you notice?
    • Create a new file in this directory with the following command: touch foo
    • Create a new user named foobar, with the option to automatically create a home directory.
    • Look at the contents of foobar's home directory. What do you notice?
  8. Be sure to record your observations in your lab notes.
  9. Issue the man pages for the useradd command. Explain the purpose of using the -e option for the useradd command. Try to think what would be the purpose for a Linux sysadmin to use this option when creating new users.

Answer the Part 2 observations / questions in your lab log book.

Part 3: Managing Groups

  1. Remain in your centos1 VM for this section.
  2. Read the man page for the groupadd and groupdel commands.
  3. Note which option allows you to set the Group ID number (GID) when you create a new group.
  4. Examine the file /etc/group
    • Which values of GID are reserved for system accounts?
    • Which values of GID are reserved for non-system user accounts?
    • What is the lowest available GID number for non-system users?
    • What is the default group name of a new user?
    • Add a new group named ops235 with a GID of 600.
    • The management at your organization have concerns regarding some irresponsible users on your system.
      • Add a new group named investigation.
      • Look at /etc/group and note the GID of group called investigation.
      • What GID is given to a new group if you do not specify it?
      • In the file, add those users to the end of the concerned group (separate each user-name with a comma).
      • Those individuals have explained their actions to management and the crisis has been resolved. Delete the investigation group.
      • Look at /etc/group again and note the change.

Answer the Part 3 observations / questions in your lab log book.

Part 4: Deleting / Modifying Users

  1. Remain in your centos1 VM for this section.
  2. Read the man page for the userdel command. Note which option automatically removes the users home directory when that user is deleted.
  3. Delete the user ops235_1 using the command userdel ops235_1
  4. Delete the user ops235_2 using the same command with the option which removes the home directory of the user.
  5. Check the contents of the /home directory. What do you notice?
  6. Check the contents of the /etc/group file. What do you notice?
  7. Read the man page for the usermod command. Note which options change the user's full name, primary group, supplementary groups, and shell.
  8. Create a new user account called noobie for the employee: "Really Green" . Assign a password for that newly created user.
  9. Management has indicated that this employee be on on probation for 3 months. Use the usermod command to set the account for noobie to expire in 3 months from this day as part of the security policy of this organization.
  10. Add each of your new users to the group ops235 (in other words, add ops235 to each user as a supplementary group).
  11. Examine /etc/group. What has changed?
  12. Use the usermod command to change the full name of the user account noobie from "Really Green" to "Outstanding Employee". Examine the result of running that command in the /etc/passwd file. What has changed?
  13. Use the usermod command to extend the use of their account for 5 years as of today.
  14. Be sure to record your observations in your lab notes.

Answer the Part 4 observations / questions in your lab log book.


INVESTIGATION 2: Managing System Services and Run-levels

Many students may think that the following topic is small and "not a big deal". Those students may say, "How hard is running and stopping services?"

The process may not be hard, but knowing how to stop, start, restart and check the status of services is absolutely critical to a Linux server. Aside from learning to trouble-shoot problems by checking the status of running services, understanding how to manage services is critical to help protect a Linux server from penetration (this term is referred to as "Hardening a system"). Sometimes it is "what we don't know" that can harm us. One key element in hardening a computer system is to disable non essential networkng services to allow IDSs (Intrusion Detection Systems) to focus on a narrower range of policy violations. A Debian-based penetration testing distribution called Kali (formerly referred to as "BackTrax") allows sysadmins and security professionals to identify vulnerabilities in their computer systems, and thus improve (harden) their systems against penetration. Learning to monitor the status, enable and disable networking services underlies the Backtrax motto:

"The quieter you are, then more you will hear..."

Part 1: How do we Manage System Services?

We have seen that maintaining unneeded packages can be a security risk due to the unnecessary increase in the complexity of your system. Similarly, it is also unnecessarily hazardous, and even more so, to leave unneeded services running. In this investigation, we will learn how to control services, and turn off those services that we think are not necessary to help reduce security risks.

  1. Use your centos2 VM for this part.
  1. Use the man pages to learn about the service command.
  2. Issue the following Linux command:
    • service --status-all
  3. Note the services that are currently running.
  4. Use the command service iptables stop to stop the service named iptables
  5. Run a command to verify that the iptables service has stopped.

    NOTE: Although the service command seems to work, it is deprecated (i.e. "out-dated:). It has been replaced by using the systemctl command. This is a command based upon a newer method of starting and managing system services called systemd (which replaces init - the "initialization table"). This method allows services to run more independently of each other, so that a service may be stopped without other dependent services to be stopped as well.

    The most common systemctl commands are shown below (it is optional to include the filename extension .service after the service-name):
    • systemctl list-units --all   (get a listing of all service names. Can pipe to grep to list service you are interested in)
    • systemctl status service-name   (Confirm status of a service - running or not-running)
    • systemctl stop service-name   (stop a service)
    • systemctl start service-name   (start a service)
    • systemctl restart service-name   (restart a service)
    • systemctl enable service-name   (enable service so service runs upon system startup)
    • systemctl disable service-name   (disable service so it does NOT run upon system startup)

  6. If you reboot now - the iptables service will be turned back on. We don't want it on though, it causes students headaches.
    To turn it off permanently we need to use the systemctl command:systemctl disable iptables
    (the chkconfig command used to be the way to enble/disable services, but is now deprecated).
  7. Use the systemctl command to verify that the iptables service is no longer running (hint: issue command, and pipe to grep "iptables").
  8. Reboot and confirm that it's no longer running.

Answer Part 1 observations / questions in your lab log book.

Part 2: How do we Manage Runlevels?

Running servers in graphical mode will make your system most likely to be penetrated. The X-windows framework can be vulnerable to attacks when these servers are connected to the Internet. This is why when you install server versions of Linux, they work in text-based mode only. Desktop versions of Linux are then installed on workstations (working in graphical mode) that connect to the server (for security reasons).

The Linux sysadmin can also change the run-level (or state) of a graphical Linux server to run in text-based mode and run the graphical mode by issuing a command when graphic mode is required. The run-level term is now deprecated in Fedora, and will likely be deprecated in RHEL/CentOS at some point as well, but for now this is what the industry is using.


  1. Perform this part in both your centos2 and centos3 VMs.
  1. Issue the following Linux command:
    • runlevel
  2. Note the difference in output between centos2 and centos3.
  3. You can use the init command to change the current run-level. See a list of runlevels here.
  4. Use the man command to learn how to use the init command. Use this command to change the current run-level in centos2 to 3. What happened?
  5. Issue the following Linux command:
    • startx
  6. What happens?
  7. Log-off your graphical system. You should return to your shell prompt.
  8. Using systemd requires a different method of setting text mode and graphical mode. You can refer to this link for future reference: How to Change Run-Levels with Systemd
  9. Restart your centos2 machine, and make certain that it runs in graphical mode
  10. Why would you want to make a graphical Linux system run in text-based mode?


Answer Part 2 observations / questions in your lab log book.


INVESTIGATION 3: LOOKING AHEAD

Automating Routine Tasks (Shell Scripting)

Idea.png
Bash Shell Scripting Tips:

  • The case statement:

    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). After action(s) are taken for a particular scenerio (or "case"), a break statement (;;) is used to "break-out" of the statement (and not perform other actions). A default case (*) is also used to catch exceptions.

    Examples (try in shell script):

    read -p "pick a door (1 or 2): " pick
    case $pick in
      1) echo "You win a car!" ;;
      2) echo "You win a bag of dirt!" ;;
      *) echo "Not a valid entry"
         exit 1 ;;
    esac


    read -p "enter a single digit: " digit
    case $digit in
      [0-9]) echo "Your single digit is: $digit" ;;
             *) echo "not a valid single digit"
                 exit 1 ;;
    esac


  • The getopts function:

The getopts function allows the shell scripter to create scripts that accept options (like options for Linux commands). This provides the Linux administrator with scripts that provide more flexibility and versatility. A built-in function called getopts (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. 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 :) and \?) cases for error handling.

Example of getopts (try in script and run with options)

while getopts abc: name
do
  case $name in
    a) echo "Action for option \"a\"" ;;
    b) echo "Action for option \"b\"" ;;
    c) echo "Action for option \"c\""
        echo Value is: $OPTARG" ;;
    :) echo "Error: You need text after -c option"
        exit 1 ;;
    \?) echo "Error: Incorrect option"
        exit 1 ;;
esac

done

We will now use shell scripting to help automate the task for a Linux adminstrator to create regular user accounts.


  1. You will be using your c7host machine for this section.
  2. Download, study, and run the following shell script. Issue the command:
    wget https://scs.senecac.on.ca/~murray.saul/user-create.bash
  3. Try to understand what these Bash Shell scripts do, and then run the script as root. After running the shell script, view the contents of the /home directory to confirm.


Although the zenity command is a "user-friendly" way to run shell scripts, Linux administrators usually create shell scripts that resemble common Linux commands. In 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 (including the use of options). Refer to the notes section on the right-hand-side for reference about the case statement and the getopts function.


  1. Open a Bash shell terminal and login as root.
  2. Use the wget command to download the input file called user-data.txt by issuing the command:
    wget https://scs.senecac.on.ca/~murray.saul/user-data.txt
  3. View the contents on the user-data.txt file to confirm there are 3 fields (username, fullname, and e-mail address)which are separated by the colon (:) symbol.
  4. Use a text editor (such as vi or nano) to create a Bash Shell script called: createUsers.bash in /root's home directory.
  5. Enter the following text content into your text-editing session:


#!/bin/bash

# createUsers.bash
# Purpose: Generates a batch of user accounts (user data stored in a text file)
#
# USAGE: /root/createUsers.bash [-i {input-path}]
#
# Author: *** INSERT YOUR NAME ***
# Date: *** CURRENT DATE ***

if [ $PWD != "/root" ] # only runs if in root's home directory
then
 echo "You must be in root's home directory." >&2
 exit 1
fi
if [ "$#" -eq 0 ] # if no arguments after command
then
 echo "You must enter an argument" >&2
 echo "USAGE: $0 [-i {input-path}]" >&2
 exit 2
fi

  1. Save your editing session, but remain in the text editor.
  2. The code displayed below uses the getopt function set the input file pathname or check for invalid options or missing option text. Add the following code



outputFlag="n"
while getopts i: name
do
 case $name in
   i) inputFile=$OPTARG ;;
   :) echo "Error: You need text after options requiring text"
       exit 1 ;;
   \?) echo "Error: Incorrect option"
        exit 1 ;;
 esac
done

  1. Save your editing session, but remain in the text editor.
  2. 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:



if [ ! -f $inputFile ]
then
  echo "The file pathname \"$inputFile\" is empty or does not exist" >&2
  exit 2
fi

set $(sed 's/ /+/g' $inputFile) # temporarily convert spaces to + for storing lines as positional parameters

for x
do
    userPassWd=$(date | md5sum | cut -d" " -f1)
    useradd -m -c "$(echo $x | cut -d":" -f2 | sed 's/+/ /g')" -p $userPassWd $(echo $x | cut -d":" -f1)
    mail -s "Server Account Information" $(echo $x | cut -d":" -f3) <<+
    Here is your server account information:
    servername: myserver.senecac.on.ca
    username: $(echo $x | cut -d":" -f1)
    password: $userPassWd
    Regards,
    IT Department
+
done

echo -e "\n\nAccounts have been created\n\n"
exit 0

  1. 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?
  2. You have completed lab4. Proceed to Completing The Lab, and follow the instructions for "lab sign-off".

Answer Investigation 3 observations / questions in your lab log book.

LAB 4 SIGN-OFF (SHOW INSTRUCTOR)

Important.png
If you have successfully completed this lab, make a new backup of your virtual machines as well as your host machine.

Arrange proof of the following on the screen:

  1. centos1 VM:
    • Account created on centos1 VM
    • List contents of /etc/group file (ops235 group)
    • List contents of /etc/passwd file (created accounts)
  2. centos2 VM:
    • Display current run-level status on centos2 VM
  3. c7host machine
    • Creation of your bash shell script called createUsers.bash
  4. Lab4 log-book filled out.


Practice For Quizzes, Tests, Midterm & Final Exam

  1. Describe all of the field in /etc/passwd
  2. What is the command to create a user? What option to create a home directory for that user?
  3. What is the command to change the full name of an already-created user?
  4. What is the command to delete a user account? What option allows for the user's home directory to be removed as well?
  5. What is the command to create a group? What is the command (or steps) to include a user in a newly-created group?
  6. What is the purpose of /etc/shadow?
  7. What is the purpose of /etc/skel?
  8. What does the term run-level mean?
  9. How to set the run-level of a Linux system to text-based only? How to set to graphical mode?
  10. What is the command to view the status of running services?
  11. What is the command to start a service (like httpd, or sshd)?
  12. What is the command to start a service?
  13. Can a service be stopped and started by issuing just one command?