Changes

Jump to: navigation, search

OPS245 Lab 2

2,719 bytes added, 17:47, 9 January 2021
m
Starting to add python investigation
'''Answer INVESTIGATION 3 observations / questions in your lab log book.'''
 
=INVESTIGATION 4: USING PYTHON TO AUTOMATE MANAGING VIRTUAL MACHINES=
===UNDER CONSTRUCTION===
This week you have added some significant capabilities to your python scripting. The ability to run loops and make decisions makes your scripts much more powerful. In this investigation you will write a python script that backs up every VM you have, regardless of its name. It will also allow the user to specify which VMs they want backed up, just in case they only want one or two.
 
<ol>
<li>In your bin directory, create the file backupVM.py, and populate with our standard beginning
<code style="color:#3366CC;font-family:courier;font-size:.9em;">
<br>
&#35;!/usr/bin/env python3
 
 
&#35; backupVM.py<br />
&#35; Purpose: Backs up virtual machines<br />
&#35;<br />
&#35; USAGE: ./backupVM.py<br />
&#35;<br />
&#35; Author: *** INSERT YOUR NAME ***<br />
&#35; Date: *** CURRENT DATE ***<br />
import os<br />
 
currentuser = os.popen('whoami')<br />
if currentuser.read() != 'root':<br />
&nbsp;&nbsp;print("You must be root")<br />
&nbsp;&nbsp;exit()<br />
else:<br />
&nbsp;&nbsp;for machine in {'centos1','centos2','centos3'}:<br />
&nbsp;&nbsp;&nbsp;&nbsp;print('Backing up' + machine)<br />
&nbsp;&nbsp;&nbsp;&nbsp;os.system('gzip < /var/lib/libvirt/images/' + machine + '.qcow2 > ~backups/' + machine + '.qcow2.gz')<br />
 
</code>
</li>
<li>Try to run that script. You'll notice it does not work. No matter what you do, it always says you are not root.</li>
<li>Modify the print statement that tells the user they must be root to also include the current username, then run the program again.</li>
<li>It should print out root, but with an axtra new-line. You may have noticed this in your other python scripts so far: the data we get from os.popen() has an extra new-line on the end. We need to modify the string it gives us a bit. See the side-bar for hints on how to do so.</li>
<li>Modify the if statement so it is just getting the current username, not the username and a newline. You can do this using several steps and several variables, but it can also be done in a single line.</li>
<li>Now that the script recognizes you as being root (or at least running the script with root permissions), it should work. Notice how we've used the + to combine several strings together to pass to the os.system command. We did this because this script needs the python variable to be evaluated before the whole line gets handed over to os.system. If you left the variable names inside the quotes, python will ignore them as just being part of a string. By putting them outside of a string, and concatenating their value to that string, we can evaluate them and feed them into that command.</li>
</ol>
 
= LAB 2 SIGN-OFF (SHOW INSTRUCTOR) =
932
edits

Navigation menu