Skip to main content

How to get started with scripting in Python

Learn to use functions, classes, loops, and more in your Python scripts to simplify common sysadmin tasks.

Python is one of the most ubiquitous development languages; it's used frequently by sysadmins, data scientists, back-end software developers, and web developers. Python has many use cases, and this tutorial explores how to use it for scripting common sysadmin tasks.

Here's the environment used in this tutorial. The operating system is Red Hat Enterprise Linux 8, 4.18.0-348.12.2.el8_5.x86_64, and the Python version is python36-3.6.8-38.module+el8.5.0+12207+5c5719bc.x86_64. Your system doesn't need to match this perfectly; all you need is some version of Python that can run the code. To download Python, you can use either your operating system's repository or get the latest version from Python.org.

The basics

To start with the basics, here is a Hello World script in Python:

$ cat hello.py3
#!/usr/bin/python3
print("hello world!")
$ python3 hello.py3
hello world!
$ echo $?
0

The first line in hello.py3 has a shebang (#) and then the path to the executable Python file.

Examine the Python interpreter via the rpm command-line interface (CLI) tool. This shows the interpreter is based on version 3.6:

$ rpm -qf /usr/bin/python3
python36-3.6.8-38.module+el8.5.0+12207+5c5719bc.x86_64
$ ll /usr/bin/python3
lrwxrwxrwx. 1 root root 25 Feb  3  2020 /usr/bin/python3 -> /etc/alternatives/python3

The second line of the Hello World script calls the print function with the argument of hello world! Print is a built-in Python function that allows users to print messages to the command line. This is especially useful for on-the-fly debugging. A function is a snippet of code that you can use without retyping it directly in your program each time you want to use it. We will dive into building custom functions shortly.

After running the Hello World script, verify a clean exit by echoing the previous command's return code:

$ echo $?
0

If there is a problem with the script, the return code will be something other than zero. You'll learn how to use those return codes in scripts later in this article.

[ Get more insight on automation by downloading the Red Hat Ansible Automation Platform 2 eBook. ]

Functions

For a slightly more advanced script, create a function called greeting and pass three arguments to it. Functions are useful for when you'll be using and reusing the same code. Rather than rewriting all of that code each time, you can put it in a function, and then you can call that function whenever you need it:

$ cat func.py3
#!/usr/bin/python3

def greeting(fname,lname,state):
	print("Hello, %s %s! How is the weather in %s?" % (fname, lname, state))

first_name = "Peter"
last_name = "Gervase"
mystate = "North Carolina"

greeting(first_name, last_name, mystate)
$ python3 func.py3
Hello, Peter Gervase! How is the weather in North Carolina?

Two aspects to note are that the order you pass the variables has to match what the function expects, and also, the number of variables passed in has to match what the function expects.

So, using:

greeting(last_name, mystate, first_name)

would make the output:

Hello, Gervase North Carolina! How is the weather in Peter?

Also, since this function expects three variables, you need to pass in exactly three variables. If you have fewer or more than three variables, then the script will fail:

$ python3 func.py3
Traceback (most recent call last):
  File "func.py3", line 10, in <module>
	greeting(first_name, last_name)
TypeError: greeting() missing 1 required positional argument: 'state'

Command-line arguments

You can use arguments passed in from the command line for the script. For this example, start by importing the sys module to gain access to its contents:

$ cat args.py3
#!/usr/bin/python3
import sys

print("you passed in", len(sys.argv), "argument(s)")
print("those arguments are: ", str(sys.argv))

print("hello", sys.argv[1])

$ python3 args.py3 Leah
you passed in 2 argument(s)
those arguments are:  ['args.py3', 'Leah']
hello Leah

As with the function examples, you must pass in the number of arguments that your script expects. If you pass in too few, then the script will fail because there is no sys.argv[1]:

$ python3 args.py3
you passed in 1 argument(s)
those arguments are:  ['args.py3']
Traceback (most recent call last):
  File "args.py3", line 7, in <module>
	print("hello", sys.argv[1])
IndexError: list index out of range

If you pass in too many, that's fine because all the script cares about is sys.argv[1]:

$ python3 args.py3 foo bar baz
you passed in 4 argument(s)
those arguments are:  ['args.py3', 'foo', 'bar', 'baz']
hello foo

[ Learn more about 30 hidden gems in Python 3. ]

Access files

Python allows access to files. To start, you can read an existing file:

$ cat file.py3
#!/usr/bin/python3

f = open("text.txt")
print(f.read())
$ cat text.txt
this is in a text file
$ python3 file.py3
this is in a text file

Classes

Classes give you the ability to assign multiple attributes to a single object. As an example, think about how you'd use variables to store information for a set of books. Would you store data in the following format: book1_title, book1_author, book2_title, and so forth? That would get unmanageable very quickly.

Using classes to keep track of that information would be much better. You could describe a book in many ways, including its title, author, length, and a summary of what the book covers. Classes allow you to build frameworks around the objects you define, as shown here in the example of a class named book:

$ cat class.py3
class book:
	name = ""
	type = "book"
	author = ""
	pages = ""
	def description(self):
    	      desc = "%s is a %s written by %s. It has %.0f pages." % (self.name, self.type, self.author, self.pages)
    	return desc

book1 = book()
book1.type = "studying book"
book1.name = "Game Theory 101"
book1.author = "William Spaniel"
book1.pages = 270
book2 = book()
book2.name = "The C Programming Language"
book2.author = "Brian Kernighan and Dennis Ritchie"
book2.pages = 272
book3 = book()
book3.type = "comic book"
book3.name = "The Days Are Just Packed"
book3.author = "Bill Watterson"
book3.pages = 175

print(book1.description())
print(book2.description())
print(book3.description())

When the code runs, you receive the following output:

$ python3 class.py3
Game Theory 101 is a studying book written by William Spaniel. It has 270 pages.
The C Programming Language is a book written by Brian Kernighan and Dennis Ritchie. It has 272 pages.
The Days Are Just Packed is a comic book written by Bill Watterson. It has 175 pages.

By creating a class named book, you can group everything for book1, book2, and book3. There are a few items to point out from this example. First, note that book2 was never assigned a specific type of book, so it used the value book from the default class information as its description. Second, note that this uses %.0f for the number of pages. If you use just %f for the number, then the output would have six zeros after the decimal. For example, the first book would have 270.000000 pages.

Subclasses

You can extend classes by using Python's subclass method. By including the object that your new class inherits from in your class definition, you can pass in existing attributes as well as define new attributes specific to extended classes. You can extend class book into multiple subclasses. For example, define a new class called Magazine:

# Definition of the subclass
# Inherits from book
class Magazine(book)
	edition=””
	volume=””
	url=””
	category=””
	# Extend the description method from class book
def description(self):  
# Define a new method to retrieve the category of the magazine
def getCategory():
	return magazine.category

Looping

Python supports using while, for, and other ways to manage flow control. You can learn more in the Python documentation. Loops allow you to repeat steps based on a fixed number of times, until a condition is met, or until a condition is no longer met. Here is an example of using while:

$ cat while.py3
#!/usr/bin/python3

i = 5

while (i > 0):
	print("the value of 'i' is: ", i)
	i = i - 1

$ python3 while.py3
the value of 'i' is:  5
the value of 'i' is:  4
the value of 'i' is:  3
the value of 'i' is:  2
the value of 'i' is:  1

Arrays

What would you do if you had a set of values that were related to each other? For that scenario, you might want to use an array. For example, if you had a list of the cars that you have owned, you could store those as an array:

mycars = ["Ford", "Chrysler", "Pontiac"]

Or, if you were keeping track of your test scores from school, you could have:

mygrades=[100,93,88,95,85,99,100,78]

To add to the array, use:

mygrades.append(100)

An example program might be:

#!/usr/bin/python3
mygrades=[100,93,88,95,85,99,100,78]
print(mygrades)
mygrades.append(100)
print(mygrades)
average = sum(mygrades) / len(mygrades)
print("the average score is %.2f" % (average))

$ python3 array.py3
[100, 93, 88, 95, 85, 99, 100, 78]
[100, 93, 88, 95, 85, 99, 100, 78, 100]
the average score is 93.11

For a more complex example, put a few of the above pieces together. This script reads domain names from an input file and then calls a function to check whether those domains are pingable. This uses a function reading from a file, using a system command, and reacting to the function's return code. Here's the script:

$ cat status.py3
#!/usr/bin/python3

import os

########################
# This script will check the status of various websites
# This could be used to verify your internet connection
# or to check if your internal servers are functioning.
#######################

def ping(mysite):
    myping = ("ping -q -c 1 %s > /dev/null" % mysite)
    status = os.system(myping)
    return(status)

with open("sites.txt") as file:
    mysites = file.readlines()

for site in mysites:
    mystatus = ping(site.strip())
    if mystatus == 0:
   	 print(site.strip() + " is fine")
    if mystatus != 0:
   	 print("********************")
   	 print("vvvvvvvvvvvvvvvvvvvv")
   	 print("%s is down!" % (site.strip()))
   	 print("^^^^^^^^^^^^^^^^^^^^")
   	 print("********************")
    print("-----------")


$ python3 status.py3
www.google.com is fine
-----------
www.pitt.edu is fine
-----------
www.redhat.com is fine
-----------
ping: www.this-is-to-simulate-a-broken-site.com: Name or service not known
********************
vvvvvvvvvvvvvvvvvvvv
www.this-is-to-simulate-a-broken-site.com is down!
^^^^^^^^^^^^^^^^^^^^
********************

Learn more

To continue learning more about Python (or any programming language), come up with a fun project to use it. Here are two suggestions:

  • Maybe you're the coach of a local youth soccer team, and you need to send out reminders each week about the upcoming game. You could put the date, the field, the time, and the opponent in a CSV file and then use Python to parse the CSV file, find the entry that matches the correct date, and email your teammates with the appropriate information.
  • Maybe each morning, you have to connect to your work VPN. You could write a Python script that first verifies you have network connectivity, stops any old VPN connections, starts a new VPN, gets a new Kerberos ticket, and then connects to an IRC server.

You might even want to make a video game using Python. Whatever learning project you decide to do, you'll be much more likely to see it through by making it meaningful and enjoyable.

Topics:   Programming   Python  
Author’s photo

Peter Gervase

I am a Senior Principal Security Architect at Verizon. Before that, I worked at Red Hat in various roles such as consulting and in the Solutions Architect where I specialized in Smart Management, Ansible, and OpenShift. More about me

Bart Zhang

Bart is a technology professional and a Red Hatter who enjoys diving into DevOps, containers, and all things Linux. Bart currently supports Red Hat's Ecosystem partners but has worked with enterprise customers of all shapes and sizes on digital transformation throughout his career. More about me

Try Red Hat Enterprise Linux

Download it at no charge from the Red Hat Developer program.