715
edits
Changes
no edit summary
# 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
* 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? <pre>echo $?</pre>
Now let's try doing the same thing in Python. Here's a sample if statement in Python.
<pre>
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!")
</pre>
=== To do ===
* 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. <pre>echo $?</pre>
* 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? <pre>echo $?</pre>
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.
== Overview ==