Book Image

Mastering Python Scripting for System Administrators

By : Ganesh Sanjiv Naik
Book Image

Mastering Python Scripting for System Administrators

By: Ganesh Sanjiv Naik

Overview of this book

Python has evolved over time and extended its features in relation to every possible IT operation. Python is simple to learn, yet has powerful libraries that can be used to build powerful Python scripts for solving real-world problems and automating administrators' routine activities. The objective of this book is to walk through a series of projects that will teach readers Python scripting with each project. This book will initially cover Python installation and quickly revise basic to advanced programming fundamentals. The book will then focus on the development process as a whole, from setup to planning to building different tools. It will include IT administrators' routine activities (text processing, regular expressions, file archiving, and encryption), network administration (socket programming, email handling, the remote controlling of devices using telnet/ssh, and protocols such as SNMP/DHCP), building graphical user interface, working with websites (Apache log file processing, SOAP and REST APIs communication, and web scraping), and database administration (MySQL and similar database data administration, data analytics, and reporting). By the end of this book, you will be able to use the latest features of Python and be able to build powerful tools that will solve challenging, real-world tasks
Table of Contents (21 chapters)

Python interpreter

Python is an interpreted language. It has an interactive console called the Python interpreter or Python shell. This shell provides a way to execute your program line by line without creating a script.

You can access all of Python's built-in functions and libraries, installed modules, and command history in the Python interactive console. This console gives you the opportunity to to explore Python. You're able to paste code into scripts when you are ready.

The difference between Python and Bash scripting

In this section, we're going to learn about the difference between Python and Bash scripting. The differences are as follows:

  • Python is a scripting language, whereas Bash is a shell used for entering and executing commands
  • Dealing with larger programs is easier with Python
  • In Python, you can do most things just by calling a one-line function from imported modules

Starting the interactive console

We can access Python's interactive console from any computer that has Python already installed. Run the following command to start Python's interactive console:

$ python

This will start the default Python interactive console.

In Linux, if we write Python in the Terminal, the python2.7 console starts. If you want to start the python3 console, then enter python3 in the Terminal and press Enter.

In Windows, when you enter Python in Command Prompt, it will start the console of the downloaded Python version.

Writing scripts with the Python interactive console

The Python interactive console starts from >>> prefix. This console will accept the Python commands, which you'll write after >>> prefix. Refer to the following screenshot:

Now, we will see how to assign values to the variable, as in the following example:

>>> name = John

Here, we've assigned a character value of John to the name variable. We pressed Enter and received a new line with >>> prefix:

>>> name = John

Now, we will see an example of assigning values to variables and then we will perform a math operation to get the values:

>>> num1 = 5000
>>> num2 = 3500
>>> num3 = num1 + num2
>>> print (num3)
8500
>>> num4 = num3 - 2575
>>> print (num4)
5925
>>>

Here, we assigned values to variables, added two variables, stored the result in a third variable, and printed the result on to the Terminal. Next, we subtracted one variable from the result variable, and the output will get stored in the fourth variable. Then, we printed the result on to the Terminal. So this tells us that we can also use the Python interpreter as a calculator:

>>> 509 / 22
23.136363636363637
>>>

Here, we performed a division operation. We divided 509 by 22 and the result we got is 23.136363636363637.

Multiple lines

When we write multiple lines of code in the Python interpreter (for example, the If statement and for and while loop functions), then the interpreter uses three dots (...) as a secondary prompt for line continuation. To come out of these lines, you have to press the Enter key twice. Now we will look at the following example:

>>> val1 = 2500
>>> val2 = 2400
>>> if val1 > val2:
... print("val1 is greater than val2")
... else:
... print("val2 is greater than val1")
...
val1 is greater than val2
>>>

In this example, we've assigned integer values to two variables, val1 and val2, and we're checking whether val1 is greater than val2 or not. In this case, val1 is greater than val2, so the statement in the if block gets printed. Remember, statements in if and else blocks are indented. If you don't use indentation, you will get the following error:

>>> if val1 > val2:
... print("val1 is greater than val2")
File "<stdin>", line 2
print("val1 is greater than val2")
^
IndentationError: expected an indented block
>>>

Importing modules through the Python interpreter

If you are importing any module, then the Python interpreter checks if that module is available or not. You can do this by using the import statement. If that module is available, then you will see the >>> prefix after pressing the Enter key. This indicates that the execution was successful. If that module doesn't exist, the Python interpreter will show an error:

>>> import time
>>>

After importing the time module, we get the >>> prefix. This means that the module exists and this command gets executed successfully:

>>> import matplotlib

If the module doesn't exist, then you will get Traceback error:

File "<stdin>", line 1, in <module>
ImportError: No module named 'matplotlib'

So here, matplotlib isn't available, so it gives an error: ImportError: No module named 'matplotlib'.

To solve this error, we will have to install matplotlib and then again try to import matplotlib. After installing matplotlib, you should be able to import the module, as follows:

>>> import matplotlib
>>>

Exiting the Python console

We can come out of the Python console in two ways:

  • The keyboard shortcut: Ctrl + D
  • Using the quit() or exit() functions

The keyboard shortcut

The keyboard shortcut, Ctrl + D, will give you the following code:

>>> val1 = 5000
>>> val2 = 2500
>>>
>>> val3 = val1 - val2
>>> print (val3)
2500
>>>
student@ubuntu:~$

Using the quit() or exit() functions

quit() will take you out of Python's interactive console. It will also take you to the original Terminal you were previously in:

>>> Lion = 'Simba'
>>> quit()
student@ubuntu$

Indentation and tabs

Indentation is a must when writing block code in Python. Indentation is useful when you are writing functions, decision-making statements, looping statements, and classes. This makes it easy to read your Python programs.

We use indentation to indicate the block of code in Python programs. To indent a block of code, you can use spaces or tabs. Refer to the following example:

if val1 > val2:
print ("val1 is greater than val2")
print("This part is not indented")

In the preceding example, we indented the print statement because it comes under the if block. The next print statement doesn't come under the if block and that's why we didn't indent it.

Variables

Like other programming languages, there's no need to declare your variables first. In Python, just think of any name to give your variable and assign it a value. You can use that variable in your program. So, in Python, you can declare variables whenever you need them.

In Python, the value of a variable may change during the program execution, as well as the type. In the following line of code, we assign the value 100 to a variable:

n = 100
Here are assigning 100 to the variable n. Now, we are going to increase the value of n by 1:
>>> n = n + 1
>>> print(n)
101
>>>

The following is an example of a type of variable that can change during execution:

a = 50 # data type is implicitly set to integer
a = 50 + 9.50 # data type is changed to float
a = "Seventy" # and now it will be a string

Python takes care of the representation for the different data types; that is, each type of value gets stored in different memory locations. A variable will be a name to which we're going to assign a value:

>>> msg = 'And now for something completely different'
>>> a = 20
>>> pi = 3.1415926535897932

This example makes three assignments. The first assignment is a string assignment to the variable named msg. The second assignment is an integer assignment to the variable named a and the last assignment is a pi value assignment.

The type of a variable is the type of the value it refers to. Look at the following code:

>>> type(msg)
<type 'str'>
>>> type(a)
<type 'int'>
>>> type(pi)
<type 'float'>

Creating and assigning values to variables

In Python, variables don't need to be declared explicitly to reserve memory space. So, the declaration is done automatically whenever you assign a value to the variable. In Python, the equal sign = is used to assign values to variables.

Consider the following example:

#!/usr/bin/python3
name = 'John'
age = 25
address = 'USA'
percentage = 85.5
print(name)
print(age)
print(address)
print(percentage)

Output:
John
25
USA
85.5

In the preceding example, we assigned John to the name variable, 25 to the age variable, USA to the address variable, and 85.5 to the percentage variable.

We don't have to declare them first as we do in other languages. So, looking at the value interpreter will get the type of that variable. In the preceding example, name and address are strings, age is an integer, and percentage is a floating type.

Multiple assignments for the same value can be done as follows:

x = y = z = 1

In the preceding example, we created three variables and assigned an integer value 1 to them, and all of these three variables will be assigned to the same memory location.

In Python, we can assign multiple values to multiple variables in a single line:

x, y, z = 10, 'John', 80

Here, we declared one string variable, y, and assigned the value John to it and two integer variables, x and z, and assigned values 10 and 80 to them, respectively.

Numbers

The Python interpreter can also act as a calculator. You just have to type an expression and it will return the value. Parentheses ( ) are used to do the grouping, as shown in the following example:

>>> 5 + 5
10
>>> 100 - 5*5
75
>>> (100 - 5*5) / 15
5.0
>>> 8 / 5
1.6

The integer numbers are of the int type and a fractional part is of the float type.

In Python, the division (/) operation always returns a float value. The floor division (//) gets an integer result. The % operator is used to calculate the remainder.

Consider the following example:

>>> 14/3
4.666666666666667
>>>
>>> 14//3
4
>>>
>>> 14%3
2
>>> 4*3+2
14
>>>

To calculate powers, Python has the ** operator, as shown in the following example:

>>> 8**3
512
>>> 5**7
78125
>>>

The equal sign (=) is used for assigning a value to a variable:

>>> m = 50
>>> n = 8 * 8
>>> m * n
3200

If a variable does not have any value and we still try to use it, then the interpreter will show an error:

>>> k
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'k' is not defined
>>>

If the operators have mixed types of operands, then the value we get will be of a floating point:

>>> 5 * 4.75 - 1
22.75

In the Python interactive console, _ contains the last printed expression value, as shown in the following example:

>>> a = 18.5/100
>>> b = 150.50
>>> a * b
27.8425
>>> b + _
178.3425
>>> round(_, 2)
178.34
>>>

Number data types store numeric values, which are immutable data types. If we do this, Python will allocate a new object for the changed data type.

We can create number objects just by assigning a value to them, as shown in the following example:

num1 = 50
num2 = 25

The del statement is used to delete single or multiple variables. Refer to the following example:

del num
del num_a, num_b

Number type conversion

In some situations, you need to convert a number explicitly from one type to another to satisfy some requirements. Python does this internally in an expression

  • Type int(a) to convert a into an integer
  • Type float(a) to convert a into a floating-point number
  • Type complex(a) to convert a into a complex number with real part x and imaginary part zero
  • Type complex(a, b) to convert a and b into a complex number with real part a and imaginary part b. a and b are numeric expressions