Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering Python Scripting for System Administrators

You're reading from   Mastering Python Scripting for System Administrators Write scripts and automate them for real-world administration tasks using Python

Arrow left icon
Product type Paperback
Published in Jan 2019
Publisher Packt
ISBN-13 9781789133226
Length 318 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Ganesh Sanjiv Naik Ganesh Sanjiv Naik
Author Profile Icon Ganesh Sanjiv Naik
Ganesh Sanjiv Naik
Arrow right icon
View More author details
Toc

Table of Contents (21) Chapters Close

Preface 1. Python Scripting Overview FREE CHAPTER 2. Debugging and Profiling Python Scripts 3. Unit Testing - Introduction to the Unit Testing Framework 4. Automating Regular Administrative Activities 5. Handling Files, Directories, and Data 6. File Archiving, Encrypting, and Decrypting 7. Text Processing and Regular Expressions 8. Documentation and Reporting 9. Working with Various Files 10. Basic Networking - Socket Programming 11. Handling Emails Using Python Scripting 12. Remote Monitoring of Hosts Over Telnet and SSH 13. Building Graphical User Interfaces 14. Working with Apache and Other Log Files 15. SOAP and REST API Communication 16. Web Scraping - Extracting Useful Data from Websites 17. Statistics Gathering and Reporting 18. MySQL and SQLite Database Administrations 19. Assessments 20. Other Books You May Enjoy

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
You have been reading a chapter from
Mastering Python Scripting for System Administrators
Published in: Jan 2019
Publisher: Packt
ISBN-13: 9781789133226
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image