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)

Parsing command-line arguments

In this section, we are going to learn about parsing arguments and the module used to parse arguments.

Command-line arguments in Python

We can start a program with additional arguments, in the command line. Python programs can start with command-line arguments. Let's look at an example:

$ python program_name.py img.jpg

Here, program_name.py and img.jpg are arguments.

Now, we are going to use modules to get the arguments:

Module

Use

Python version

optparse

Deprecated

< 2.7

sys

All arguments in sys.argv (basic)

All

argparse

Building a command-line interface

>= 2.3

fire

Automatically generating Command-Line Interfaces (CLIs)

All

docopt

Creating CLIs interfaces

>= 2.5

Sys.argv

The sys module is used to access command-line parameters. The len(sys.argv) function contains the number of arguments. To print all of the arguments, simply execute str(sys.argv). Let's have a look at an example:

01.py
import sys
print('Number of arguments:', len(sys.argv))
print('Argument list:', str(sys.argv))

Output:
Python3 01.py img
Number of arguments 2
Arguments list: ['01.py', 'img']