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)

Modules

Modules are just files that contain Python statements and definitions. A file that contains Python code (for example, sample.py) is called a module and its module name would be sample. Using modules, we can break larger programs into small and organized ones. An important feature of a module is re-usability. Instead of copying the definitions of the most used functions in different programs, you can define them in the module and just import them whenever needed.

Let's create a module and import it. We will create two scripts: sample.py and add.py. We will import a sample module in our add.py. Now, save the following code as sample.py. Let's take a look with the following example:

sample.py
def addition(num1, num2):
result = num1 + num2
return result

Here, we have defined a addition() function inside a module named sample. The function takes in two numbers and returns their sum. Now we have created a module. You can import this in any Python program.

Importing modules

Now, after creating a module, we will learn how to import that module. In the previous example, we created a sample module. Now we will import the sample module in add.py script:

add.py
import sample
sum = sample.addition(10, 20)
print(sum)

Output:
30