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)

Understanding lists

Python supports a data structure called list, which is a mutable and ordered sequence of elements. Each element in that list is called as item. Lists are defined by inserting values between square brackets [ ]. Each element of list is given a number, which we call as a position or index. The index starts from zero; that is, the first index is zero, the second index is 1, and so on. We can perform the following operations on lists: indexing, slicing, adding, multiplying, and checking for membership.

Python's built-in length function returns the length of that list. Python also has function for finding the largest and smallest item of list. Lists can be numbered lists, string lists, or mixed list.

The following is the code for creating a list:

l = list()
numbers = [10, 20, 30, 40]

animals = ['Dog', 'Tiger', 'Lion']
list1 = ['John', 5.5, 500, [110, 450]]

Here, we've created three lists: the first is numbers, the second is animals, and the third is list1. A list within another list is called as nested list. Our list1 is a nested list. A list containing no elements is called an empty list; you can create one with empty brackets, [].

As you might expect, you can assign list values to variables:

>>> cities = ['Mumbai', 'Pune', 'Chennai']
>>> numbers_list = [75, 857]
>>> empty_list = []
>>> print (cities, numbers_list, empty_list)
['Mumbai', 'Pune', 'Chennai'] [75, 857] []

Accessing values in lists

We can access the values from a list by using index values. We will specify the index number in [ and ]. Index starts from 0. Refer to the given example:

#!/usr/bin/python3
cities = ['Mumbai', 'Bangalore', 'Chennai', 'Pune']
numbers = [1, 2, 3, 4, 5, 6, 7 ]
print (cities[0])
print (numbers[1:5])


Output:
Mumbai
[2, 3, 4, 5]

Updating lists

You can update elements of lists, as shown in the following code:

#!/usr/bin/python3
cities = ['Mumbai', 'Bangalore', 'Chennai', 'Pune']
print ("Original Value: ", cities[3])
cities[3] = 'Delhi'
print ("New value: ", cities[3])


Output:
Original Value: Pune
New value: Delhi

Deleting list elements

To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting. You can use the remove() method if you do not know exactly which items to delete. Refer to the following example:

#!/usr/bin/python3
cities = ['Mumbai', 'Bangalore', 'Chennai', 'Pune']
print ("Before deleting: ", cities)
del cities[2]
print ("After deleting: ", cities)

Output:
Before deleting: ['Mumbai', 'Bangalore', 'Chennai', 'Pune']
After deleting: ['Mumbai', 'Bangalore', 'Pune']

Basic list operations

There are five basic list operations:

  • Concatenation
  • Repetition
  • Length
  • Membership
  • Iteration

Description

Expression

Result

Concatenation

[30, 50, 60] + ['Hello', 75, 66]

[30,50,60,'Hello',75,66]

Membership

45 in [45,58,99,65]

True

Iteration

for x in [45,58,99] : print (x,end = ' ')

45 58 99

Repetition

['Python'] * 3

['python', 'python', 'python']

Length

len([45, 58, 99, 65])

4

List operations

In this section, we are going to learn about basic list operations: concatenation and repetition.

The + operator concatenates lists:

>>> a = [30, 50, 60]
>>> b = ['Hello', 75, 66 ]
>>> c = a + b
>>> print c
[30,50,60,'Hello',75,66]

Similarly, the * operator repeats a list a given number of times:

>>> [0] * 4
[0, 0, 0, 0]
>>> ['Python'] * 3
['python', 'python', 'python']

Indexing, slicing, and matrices

List indices work the same way as string indices. Values can be accessed using index. If you try to read or write an element that does not exist, you get IndexError. If an index has a negative value, it counts backward from the end of the list.

Now, we will create a list named cities and we will see the index operations:

cities = ['Mumbai', 'Bangalore', 'Chennai', 'Pune']

Description

Expression

Results

Index start at zero

cities[2]

'Chennai'

Slicing: getting sections

cities[1:]

['Bangalore', 'Chennai', 'Pune']

Negative: count from the right

cities[-3]

'Bangalore'