OPS245 Scripting Exercises Lab 2 dev
Contents
- 1 Key Concepts
- 2 Virtual Machine Backup Script
- 2.1 Overview
- 2.2 Filling in the code
- 2.2.1 Importing the required modules
- 2.2.2 Storing the output of the current user and checking to see if they are root.
- 2.2.3 Check the current user (who is executing the script) and store the information in the variable "currentuser".
- 2.2.4 Checking if the current user is root
- 2.2.5 Asking the user which VM they wish to backup, and performing the backup
- 2.2.6 Error checking
- 2.2.7 Else, we are doing a full backup (all 3 VMs)
- 2.2.8 Exit with success
Key Concepts
Conditional Logic
Condition Logic aka Control Flow statements aka If statements are an important scripting and programming concept. They allow us to make scripts more flexible by building in decision making. You learned how to use these in BASH scripting in ULI101, but lets review the basics. You use an if statement to check whether a condition is met (or not, depending on how you write it) and execute some code (or not) based on that condition. Here is a sample if statement in Bash:
#!/bin/bash # Author: Jason Carman # Date: January 26, 2023 # Purpose: Check to see if user is root, if they are not inform them they should run the script as root and exit with an error (non-zero) status code # Usage: ./checkuser.bash # # Check the output of the whoami command to determine if they are root if [[ $(whoami) == "root" ]]; then echo "You are root!" # Else, they are not root. Display a message and exit with a non-zero status code else # Display a message indicating the script should be run as root echo "You are not root. Please run the script with root permissions." # Exit with a non-zero status code indicating an error exit 1 fi
To do: sample Bash script
- Copy the above code and give it execute permission using the chmod command.
- Try running it as a regular user. What happens?
- After running it as a regular user, from the command line type the following and observer the output.
echo $?
- Now try running the script using sudo. What happens?
- From the command line type the following and observe the output. What is different from the previous output?
echo $?
Now let's try doing the same thing in Python. Here's a sample if statement in Python.
thor: Jason Carman # Purpose: Check to see if the user is root, if they are not inform them they should run the script as root and exit with an error (non-zero) status code # Usage: ./checkuser.py # # Import the Operating System and sys modules import os, sys # Check if the user is root using an if statement if os.geteuid() != 0: # Display a message indicating the script should be run as root and exit sys.exit("You must be root. Please run the script with root permissions") # Else else: # User is root, print a message print("You are root!")
To do: sample Python script
- Copy the above code and give it execute permission using the chmod command.
- Try running it as a regular user. What happens?
- After running it as a regular user, from the command line type the following and observer the output.
echo $?
- Now try running the script using sudo. What happens?
- From the command line type the following and observe the output. What is different from the previous output?
echo $?
There is one interesting difference between the two scripts. In BASH you can control what number the script uses to indicate an error. In Python (with sys.exit anyway) you cannot. In Python you can exit indicating success by calling sys.exit() with nothing in the parentheses.
Virtual Machine Backup Script
Overview
In Lab 2 Investigation 3 you performed a manual backup of all 3 virtual machines. While this is something both important and necessary, it's a tedious process. This is something you could automate through scripting. In this exercise you are going to write a script that will backup all three of your virtual machines. We will improve on this backup script in a later exercise. To begin, open your text editor (vi) on c7host and copy the following template in. Be sure to modify Author and Date with the correct information.
#!/usr/bin/env python3 # Author: Your Name; youremail@myseneca.ca # Date: # Purpose: Backs up virtual Machines # Usage: ./backupVM.py # # Import the Operating System (os) module, Subprocess module and Sys module # Store the output of the whoami command as a variable called whoami # Check the current user (who is executing the script) and store the information in the variable currentuser. The os.geteuid() command requests the current user ID from the operating system. Root has a UID of (0). Users have non-zero values, usually starting at 1000. We can use this to check if the current user is root or not. # Using an if statement check if currentuser is not equal to 0 # Print a message telling the user who they are. Use , to concatenate (join) the message and the whoami variable # Exit with an error message indicating they must be root # Else (they are root, we can continue) # Prompt the user asking if they wish to back all VMs, accepting options y for yes or n for no. Store the answer in the variable backupAll # If backupAll equals "n" # Prompt the user asking which VM they wish to backup. Store the answer in the variable backupVM # If backupVM equals "centos1" # Print "Backing up centos1" # Use os.system to call the virsh dumpxml command you used for centos1 in Lab 2 Investigation 3 # Use os.system to compress (using gzip) the .qcow2 for centos1, using the same syntax as in Lab 2 Investigation 3 # Else if (elif) backupVM equals "centos2" # Print "Backing up centos2" # Use os.system to call the virsh dumpxml command you used for centos2 in Lab 2 Investigation 3 # Use os.system to compress (using gzip) the .qcow2 for centos2, using the same syntax as in Lab 2 Investigation 3 # Else if (elif) backupVM equals "centos3" # Print "Backing up centos2" # Use os.system to call the virsh dumpxml command you used for centos3 in Lab 2 Investigation 3 # Use os.system to compress (using gzip) the .qcow2 for centos3, using the same syntax as in Lab 2 Investigation 3 # Else, user has entered an invalid choice # Display a message indicating an invalid choice has been made and give the valid options (centos1, centos2, centos3) and exit # Else, we're doing a full backup (backing up all 3 virtual machines: centos1, centos2, centos3) # Print "Backing up centos1" # Use os.system to call the virsh dumpxml command you used for centos1 in Lab 2 Investigation 3 # Use os.system to compress (using gzip) the .qcow2 for centos1, using the same syntax as in Lab 2 Investigation 3 # Print "Backing up centos2" # Use os.system to call the virsh dumpxml command you used for centos2 in Lab 2 Investigation 3 # Use os.system to compress (using gzip) the .qcow2 for centos2, using the same syntax as in Lab 2 Investigation 3 # Print "Backing up centos3" # Use os.system to call the virsh dumpxml command you used for centos3 in Lab 2 Investigation 3 # Use os.system to compress (using gzip) the .qcow2 for centos2, using the same syntax as in Lab 2 Investigation 3 # Exit successfully
Filling in the code
The below instructions provide all (or most) of the required code for filling in the above template. Fill in each section in sequence under the appropriate comment block.
Importing the required modules
For this script we will require the following modules:
- os
- system
- sys
Using the import statement (like we have done previously), import the above modules on one line.
import os, system, sys
Storing the output of the current user and checking to see if they are root.
We will use this to indicate an error if the script is not being run as root (without sudo). Create a variable called "whoami" and store the output of the whoami command in it. We will use the subprocess module, with the check_output function to accomplish this task.
whoami = subprocess.check_output("whoami").decode("utf-8")
Check the current user (who is executing the script) and store the information in the variable "currentuser".
We will use the os.geteuid() function for this task. Linux UID's (User IDs) start at 1000 for users. Root has a UID of 0.
currentuser = os.geteuid()
Checking if the current user is root
Now that we have the information about the current user and their UID stored in variables, we can check to see if the user is root using an if/else block. If the user is not root, we will print an error (indicating they are not root and who they are currently logged in as) and exit with an error. You can use the "sys.exit()" function to display an error and exit. If no content is provided with sys.exit, the script will exit with a 0 status code. If content is provided it will display that error on the screen and exit with a 1 status code. Remember that Linux uses 0 status codes to indicate success and any non-zero value to indicate failure.
if currentuser != 0: print("You are currently logged in as:",whoami) sys.exit("You must be root")
We can use an else statement to continue, since the above checks to see if the user is not root. If the above condition is not met, the current user's UID is 0 and they are root. We can then prompt if they want to backup all VMs or not. If the answer is no, prompt again asking which VM they wish to backup.
else: backupAll=input("Do you wish to backup all VMs? (y | n) ")
Asking the user which VM they wish to backup, and performing the backup
If the user selected no above, we need to know what VM they wish to backup. We will prompt again and use a nested if statement to check their response. Then, perform the desired backup.
if backupAll == "n": backupVM=input("What VM do you wish to backup? ") if backupVM == "centos1": print("Backing up centos1") os.system("virsh dumpxml centos1 > /home/jmcarman/backups/centos1.xml") os.system("gzip < /var/lib/libvirt/images/centos1.qcow2 > /home/jmcarman/backups/centos1.qcow2.gz") elif backupVM == "centos2": # Repeat above steps with replacing centos1 with centos2
Using the above sample, add the steps to backup centos2 or centos3 if appropriate.
Error checking
If the user submits an invalid VM name (not centos1, centos2 or centos3) we should generate an error and exit.
else: sys.exit("Invalid choice, your VM options are centos1, centos2, centos3")
Else, we are doing a full backup (all 3 VMs)
Use the below sample to back up centos1. Modify it for centos2 and centos3.
print("Backing up centos1") os.system("virsh dumpxml centos1 > /home/jmcarman/backups/centos1.xml") os.system("gzip < /var/lib/libvirt/images/centos1.qcow2 > /home/jmcarman/backups/centos1.qcow2.gz")
Exit with success
Finally, we should exit successfully. This isn't technically necessary, but is a good practice.
sys.exit()