6.Python Scripting
6.Python Scripting
1. Python Introduction
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is
designed to be highly readable.
So why is python tutorial in this book?
When we were writing bash script for doing automation, slowly we increased the complexity of our
code. Our code became more and more complex. Also, we do not have any other feature in bash
scripting apart from just automating Linux tasks.
Python is among the easiest programming language out there.
Being easy it gives us lots of feature and libraries which extends the power of python. Python is
very extensible. We can use python to run Linux automation, windows automation, Cloud
automation and several others. It’s very versatile in nature.
Python is Interpreted: Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it. This is similar to PERL and PHP.
Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter,
directly to write your programs.
Python is Object-Oriented: Python supports Object-Oriented style or technique of programming
that encapsulates code within objects.
Python is a Beginner's Language: Python is a great language for the beginner-level programmers
and supports the development of a wide range of applications from simple text processing to WWW
browsers to games.
Installing python.
Windows Installation
Here are the steps to install Python on Windows machine.
Open a Web browser and go to http://www.python.org/download/. Follow the link for the Windows
installer python-XYZ.msi file where XYZ is the version you need to install.
To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0.
Save the installer file to your local machine and then run it to find out if your machine supports
MSI.
Linux Installation
Linux system by default comes with python installed so it is not required to take any action for
Linux system.
2. Basic Syntax
Type the following text at the Python prompt and press the Enter:
Python scripting
Create a file named hello.py, py stands for python and is extension of python script file.
Add below mentioned content and save file.
#!/usr/bin/python
Line 1- #! is the shebang charect as we know from bash scripting, Interpreter path is
/usr/bin/python. You can find python interpreter path in your Linux system by giving “which
python”. Invoking the interpreter with a script parameter begins execution of the script and
continues until the script is finished. When the script is finished, the interpreter is no longer active.
The 3 line program above is correct and will run producing the expected output.
The program below will generate a syntax error
because of the space character inserted at the start of the second line.
print “Python is a scripting language.”
Python evaluate the second print statement as a block of code inside first print statement. So its
thinking seond print is under first print statement but its a separate statement.
Python provides no braces to indicate blocks of code for class and function definitions
or flow control. Blocks of code are denoted by line indentation, which is rigidly
enforced.
The if statement
The if statement starts with the keyword "if"
if x == 30:
else:
Under the if statement, the statements to be run if the condition is true are entered.
after typing a few space characters. In the example above, two space characters are used.
Any statements to be run after the else: part of the program also have to be spaced out to the
***same level*** by typing 2 space characters before the statement.
The number of spaces in the indentation is variable, but all statements within the block must be
indented the same amount. For example:
if True:
print "True"
else:
print "False"
print "Answer"
print "True"
else:
print "Answer"
print "False"
Thus, in Python all the continuous lines indented with same number of spaces would
form a block.
Note: Do not try to understand the logic at this point of time. Just make sure you
understood various blocks even if they are without braces.
• Double (")
Double quotes can be used when you have a variable in the string that needs to be evaluated
by python using string formating(%).
For example:
word = 'word'
Comments in Python
A hash sign (#) is a comment symbol in python. Python ignores all the text after # and does not
evaluate it. All characters after the # and up to the end of the physical line are part of the comment
and the
Python interpreter ignores them.
#!/usr/bin/python
# First comment
# second comment
Multiline Comment.
We can use paragraph string to create a multiline comment. Everything inside paragraph string
would be ignored by Python.
#!/usr/bin/python
num = 84
by python"""
3. Variable Types
Variable are temporary storage for data in memory. There are different kinds of data, by assigning
different data types to variables, you can store integers, decimals, or characters in these variables.
Variable Assignment.
We don’t need to define variable types in python like other programming language. Variable
declaration happens automatically when we assign a value to a variable.
The equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the right of
the = operator is the value stored in the variable.
For example:
#!/usr/bin/python
print myfloatnumber
print myname
Here 86. 86.11 & imran are values assigned to variables names mynumber, myfloatnumber &
myname respectively. Execute the above script and check the output.
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously. For
example:
x = y = z= 86
Here, an integer object is created with the value 86, and all three variables are assigned to the same
memory location.
Here, two integer objects with values 86 and 11 are assigned to variables x and y respectively, and
one string object with the value "imran" is assigned to the variable z.
• Numbers
• String
• List
• Tuple
• Dictionary
Strings
strvar2 = ‘string#2’
strvar2 = “string#2”
String slicing can also be done and stored into a variable, slice means subset or part of the string.
Subsets of strings can be done by slice operator ([ ] and [:] ) with indexes starting at
0 in the beginning of the string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator.
For example:
#!/usr/bin/python
Hello DevOps!
Hello
DevOps
llo DevOps!
For example:
#!/usr/bin/python
ansible
aws
['puppet', 86.96]
Tuples
ansible
(1111, 'puppet')
The following code is invalid with tuple, because we attempted to update a tuple,
which is not allowed. Similar case is possible with lists:
#!/usr/bin/python
Dictionary
In dictionary data in stored in format of key-value pair unlike list or tuple where we just have
values. You can think it a any normal english dictionary where word in the key and its meaning is
its value.
Python's dictionaries are kind of hash table type. A dictionary key can be almost any Python type,
but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.
Visualpath Training & Consulting.
Flat no: 205, Nilgiri Block,Aditya Enclave, Ameerpet, Hyderabad, Phone No: - +91-970 445 5959, 961 824 5689 E-
Mail ID : [email protected], Website : www.visualpath.in.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces ([]).
For example:
#!/usr/bin/python
dict1 = {}
dict1['profile'] = "hitman"
dict1['passcode'] = "zeus"
zeus
Dictionaries have no concept of order among elements. It is incorrect to say that the
elements are "out of order"; they are simply unordered.
4. Python Operators
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called
operator.
Types of Operators
Python language supports the following types of operators.
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
a = 2
b = 30
if ( a == b ):
else:
if ( a != b ):
else:
if ( a < b ):
else:
if ( a > b ):
else:
a is not equal to b
a is not equal to b
a is less than b
a is not greater than b
Example
Visualpath Training & Consulting.
Flat no: 205, Nilgiri Block,Aditya Enclave, Ameerpet, Hyderabad, Phone No: - +91-970 445 5959, 961 824 5689 E-
Mail ID : [email protected], Website : www.visualpath.in.
#!/usr/bin/python
a = 10
b = 20
list = [1, 2, 3, 4, 5 ];
if ( a in list ):
else:
if ( b not in list ):
else:
a = 2
if ( a in list ):
else:
5. Decision Making
Decision making is there in every programming language. Based on a test case the program decides
to execute statements/commands or not. In python we use if, elif and else keywords to make
decisions.
Syntax
code
If the test case is true then the code in if block gets executed.
If the text expression is false, the statement(s) is not executed.As we have seen previously in
indentation section to create a block of code underneath any statement we indent the code or we
give spaces to it.
For example, the print statement comes under the if block.
if True:
#!/usr/bin/python
# If the number is
positive, we print an
appropriate message
num = 30
if num == 30:
num = 82
Syntax of if/else
if test case:
Body of if
else:
Body of else
The if/else statement evaluates test case and will execute body of if only when test condition is true.
If the condition is false body of else is executed.
Python if. Else Flowchart
#!/usr/bin/python
# Program checks
if the number is
positive or negative
num = -4
if num >= 0:
else:
Syntax of if/elif/else
if test case:
Body of if
Body of elif
else:
Body of else
If the condition is false else block gets executed but what if we want to evaluate few more condition
and then decide the execution. We can use elif to put more condtions in out decision making
process its short form of else if.
If the condition for if is False, it checks the condition of the next elif block and so on.
If all the conditions are False, body of else is executed.
The if block can have only one else block. But it can have multiple elif blocks.
Flowchart of if...elif...else
#!/usr/bin/python
# In this program,
# less than 10
else:
6. Loops
Loops are used when you have a block of code that you want to repeat it for fixed number of time
or until a condition is not satisfied.
Python provides us with two loops
While loop: Repeat the block of code untill the while condition is true.
while test_case:
Body of while
Body of for
For loops are traditionally used when you have a block of code which you want to repeat a fixed
number of times. The Python for statement iterates over the members of a sequence in order,
executing the block each time. Contrast the for statement with the ''while'' loop, used when a
condition needs to be checked each iteration, or to repeat a block of code forever. For example:
while True:
print "To infinity and beyond! We're getting close, on %d now!" % (x)
x += 1
While Loops
count = 0
count = count + 1
For loops
For loop can iterate over any sequences like list, tuple or string which are indexed. Every element in
these datatypes are indexed can be iterated over. This process of iterating over a sequence is also
called as traversing or traversal in nature.
Body of for
Here, variable1 is the variable that takes the value of the item inside the sequence on each iteration.
#!/usr/bin/python
print “Bye!”
Flowchart of break
The working of break statement in for loop and while loop is shown below.
# First Example
if word == 't':
break
a = 10
# Second Example
while a > 0:
a = a -1
if a == 5:
break
Current Letter : P
Current Letter : y
Execution completed!
Flowchart of continue
The working of continue statement in for and while loop is shown below.
#!/usr/bin/python
# First Example
if word == 't':
continue
a = 10
# Second Example
while a > 0:
if a == 5:
continue
Current Letter : P
Current Letter : y
Current Letter : h
Current Letter : o
Current Letter : n
Execution completed!
7. Built In Methods/Functions
Python has numerous built in methods that extends its capabilities. Listed below are few of the
useful built in methods on all the DataType.
Check Python docs for the list of all the methods and its uses.
String
str2 = "exam";
print str1.find(str2);
a.rstrip()
Hello
split: Splits string according to delimiter str (space if not provided) and
returns list of substrings; split into at most num substrings if given.
str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( );
Lists
aList.append( 2009 );
aList.extend(bList)
aList.insert( 3, 2009)
pop: Removes element from list at a specified index value, default is last element.
aList = [123, 'xyz', 'zara', 'abc'];
Dictionary
8. Functions
A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing.
We have already used some built in functions like range(), len(), type() etc. We will learn now how
to write our own functions.
Functions rules
Function block begins with the keyword def followed by function name and parantheses.
Syntax
def func_name()
code block
Keyword “return” in the code block exits the function and can return some value, if no value is
returned default return value is “None”.
Syntax
def func_name(arg1,arg2):
code block
return variable
def func_name(arg1,arg2):
code block
print var1
return
# Calling print_func
print returnedvalue
Output
Testing function calling.
None
None
Function Arguments
You can call a function by using the following types of formal arguments:
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
Required Arguments
Required arguments are the arguments passed to a function in correct positional order. Here, the
number of arguments in the function call should match exactly with the function definition.
To call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax
error as follows:
#!/usr/bin/python
print str;
return;
printme();
Keyword Arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a
function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter is able
to use the keywords provided to match the values with parameters.
You can also make keyword calls to the printme() function in the following ways
#!/usr/bin/python
print str;
return;
The following example gives more clear picture. Note that the order of parameters
does not matter.
#!/usr/bin/python
return;
Age
miki
50
Default Arguments
A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument. The following example gives an idea
on default arguments, it prints default age if it is not passed:
#!/usr/bin/python
return;
printinfo( name="miki" );
Age
50
Name:
Age
miki
miki
35
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all non keyword variable
arguments. This tuple remains empty if no additional arguments are specified during the function
call. Following is a simple example:
#!/usr/bin/python
print arg1
print var
return;
printinfo( 10 );
10
Output is:
70
60
50
return total;
9. Modules
Modules in Python are simply Python files with the .py extension, which implement a set of
functions. Modules are imported from other modules using the import command.
We use modules to break down large programs into small manageable and organized files.
Furthermore, modules provide reusability of code.
We can define our most used functions in a module and import it, instead of copying their
definitions into different programs.
Example script name is modexa.py
imran@DevOps:/tmp$ cat modexa.py
c = a * b
return c
def hello():
For example, to import the function fibonacci from the module fib, use the following statement:
from fib import fibonacci
This statement does not import the entire module fib into the current namespace; it just introduces
the item fibonacci from the module fib into the global symbol table of the importing module.
This provides an easy way to import all the items from a module into the current
#!/usr/bin/python
# Import built-in module math
import math
content = dir(math)
print content;
Here, the special string variable __name__ is the module's name, and __file__ is the.
filename from which the module was loaded.
Python is very widely used as a scripting language to automate day to day system admin tasks or
even a full scale Orchestration of multiple systems.
The OS module in Python provides a way of using operating system dependent functionality.
The functions that the OS module provides allows you to interface with the underlying operating
system that Python is running on. (Windows, Mac or Linux.
You can find important information about your location or about the process.
Before we start, make sure that you have imported the OS module "import os"
OS Functions explained`
os.system(“ls”) # Executing a shell command
OS Functions Examples
path = "/tmp/pysys"
if os.path.isdir(path):
if os.path.isfile(path):
Creates a directory
print os.mkdir('devopsdir', 0750)
print root
print dirs
print files
What is Fabric?
As the README says:
Installing Fabric
Fabric module does not comes inbuilt in python but can be installed with python package manager
like “pip”.pip is a package management system used to install and manage software
packages written in Python.
First we have to install pip.
Do I need to install pip?
pip is already installed if you're using Python 2 >=2.7.9 or Python 3 >=3.4 binaries downloaded
from python.org, but you'll need to upgrade pip.
Task arguments
It’s often useful to pass runtime parameters into your tasks, just as you might during regular Python
programming.
Fabric functions
Fabric provides a set of commands in fabric API that are simple but powerful.
def hello(name="world"):
def calling_local():
local("ls -ltr")
def test_run():
run("touch /tmp/testdir/file86")
def test_sudo():
def test_put():
put("devfile4", "/home/vagrant/")
# Takes user input & pull file from remote machine to local machine.
def test_get():
This remote server information can also be added into the fabfile by using env.hosts, env.user and
env.password variables which we will see in next example.
with cd("/tmp/"):
The lcd context manager (local cd) works very similarly to one above (cd); however, it only
affects the local system's state.
with lcd("/opt/nexus"):
put("nexus.tar.gz", "/tmp/nexus.tar.gz")
env.hosts=['192.168.1.9']
env.user='vagrant'
env.password='vagrant'
def apache_install():
def apache_start():
def apache_enable():
def push_index():
def apache_restart():
def disable_firewall():
def assemble_apache():
apache_install()
apache_start()
apache_enable()
push_index()
apache_restart()
disable_firewall()
# Define all the fabric methods to clean apache setup in just one function.
def dismantle_apache():
From the above script, we have seen that initially while doing setup we have given only one fabric
method in one function. But while dismantling/cleaning apache we have given all the required
fabric method in just one function. Both the approach works fine but if I have separate function to
start or install apache or setup firewall rule I can also call them individually from bash shell. This is
very convenient if I have just start apache on an array of remote host I already have a separate
function defined for it. Like this we can reuse this code for some other tasks also.
cat context.xml
<Context antiResourceLocking="false" privileged="true" >
<!--
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
-->
</Context>
cat fabfile.py
# Author: Srini Vas
import boto
def update():
sudo("apt-get update -y")
sudo("sudo apt-get install default-jdk -y")
def tomcat8():
sudo("apt-get install tomcat8 -y")
def admin():
sudo ("apt-get install tomcat8-docs tomcat8-examples tomcat8-admin")
def user_tom():
put("tomcat-users.xml" , "/var/lib/tomcat8/conf", use_sudo = True)
def user_manage():
put("context.xml", "/var/lib/tomcat8/webapps/ROOT/META-INF/", use_sudo = True)
def start():
sudo("systemctl start tomcat8")
def restart():
sudo("systemctl restart tomcat8")
def fab_tom():
update()
tomcat8()
admin()
user_tom()
user_manage()
start()
ufw_stop()
def add_key_rep():
sudo("wget -q -O - https://pkg.jenkins.io/debian/jenkinsci.org.key | sudo apt-key add -")
sudo("sudo sh -c 'echo deb http://pkg.jenkins.io/debianstable binary/ >
/etc/apt/sources.list.d/jenkins.list'")
sudo("sudo add-apt-repository ppa:openjdk-r/ppa -y")
def apt_get_update():
sudo("sudo apt-get update")
def jenkins_git_maven_install():
sudo("sudo apt-get install openjdk-7-jdk -y")
sudo("sudo apt-get install jenkins -y")
sudo("sudo apt-get install git -y")
sudo("sudo apt-get install maven -y")
def jenkins_git_maven_status():
sudo("sudo service jenkins status")
def jenkins_restart():
sudo("sudo service jenkins restart")
def jenkins_firewall():
sudo("service ufw stop")
def jenkins_setup():
add_key_rep()
apt_get_update()
jenkins_git_maven_install()
jenkins_start()
jenkins_git_maven_status()
jenkins_firewall()
Creating a bucket
>>> bucket = s3.create_bucket('boto-demo-%s' % int(time.time()))
>>> mybucket.list()
Ec2 Interface
Creating a Connection
The first step in accessing EC2 is to create a connection to the service. The recommended way of
doing this in boto is:
>>> import boto.ec2
>>> conn = boto.ec2.connect_to_region("us-west-2")
Launching Instances
To launch an instance and have access to it, you need to first setup security group and key pair.
Now, let’s say that you already have a key pair, want a specific type of instance, and you have your
security group all setup. In this case we can use the keyword arguments to accomplish that:
>>> conn.run_instances(
'<ami-image-id>',
key_name='your-key-name-here',
instance_type='t2.micro',
security_groups=['your-security-group-here'])
Stopping Instances
If you want to stop/shut down an instance, get its instance id and supply that as keyword argument.
Terminating Instances
Similar to terminate an instance pass istance id’s.
>>> conn.delete_snapshot(snapshot.id)
True
import boto
## Variables
region =
ami_id =
login_key_name =
inst_type =
sbnet_id =
inst_name =
conn = boto.ec2.connect_to_region(region)
inst_id = ins.instances[0]
inst = str(inst_id)
eip = conn.allocate_address(domain='vpc')
status = inst_id.update()
time.sleep(10)
status = inst_id.update()
if status == 'running':
inst_id.add_tag("Name",inst_name)
conn.associate_address(inst[9:],eip[8:])
else:
import boto.dynamodb2
import sys
env='Tesla'
def except_func(e):
e_dict=e.__dict__['message']
return None
else:
print e_dict
sys.exit()
#sprint4
try:
UserDisLikeProducts = Table.create(env+'AltCurrent',
schema=[HashKey('UserId'),RangeKey('ProductUrl')], connection=conn);
except Exception as e:
print except_func(e)
import boto
import jenkins
import getpass
conn = boto.beanstalk.connect_to_region('us-west-2')
bean_info = conn.describe_applications(application_names=bean_name)
bean_list_info =
bean_info['DescribeApplicationsResponse']['DescribeApplicationsResult']['Applica
tions']
if not bean_list_info:
else:
print "%s stalk already exists, please delete the stalk and run the script
again." % bean_name
exit()
conn.create_application(bean_name, description=bean_name)
conn.create_application_version(bean_name, 'Sample_Application')
conn.create_environment(bean_name, bean_name,
version_label='Sample_Application', solution_stack_name='64bit Windows Server
2012 R2 running IIS 8.5', cname_prefix=bean_name, description=None,
option_settings=[('aws:autoscaling:launchconfiguration', 'Ec2KeyName',
'testdigitaltestApp'), ('aws:autoscaling:launchconfiguration',
'IamInstanceProfile', 'aws-elasticbeanstalk-ec2-
role'),('aws:autoscaling:updatepolicy:rollingupdate', 'RollingUpdateEnabled')],
options_to_remove=None, tier_name='WebServer', tier_type='Standard',
tier_version='1.0')
time.sleep(10)
dict = conn.describe_events(application_name=bean_name,
environment_name=bean_name)
time.sleep(3)
event1 =
dict['DescribeEventsResponse']['DescribeEventsResult']['Events'][0]['Message']
event2 =
dict['DescribeEventsResponse']['DescribeEventsResult']['Events'][0]['Message']
print event1
dict = conn.describe_events(application_name=bean_name,
environment_name=bean_name)
if 'Error' in event1:
print event1
exit()
if event1 != event2:
print event2
event1 =
dict['DescribeEventsResponse']['DescribeEventsResult']['Events'][0]['Message']
event2 =
dict['DescribeEventsResponse']['DescribeEventsResult']['Events'][0]['Message']
Summary:
• Python is an interpreted language, its highly extensible and comes with lot of goodies.
• Python is very easy to read and write compared to any other programming language.
• Numbers, Strings, List, Tuples & Dictionary are python data types. Python comes with lot
of methods that be applied on these datatypes to manipulate or present data in different
ways.
• Decision making(if/elif/else) and loops(for&while) in python has a very simple syntax and
block of code inside them are indented mostly two or three spaces.
• Python functions are used when we want to group some code together and have it accessible
from any other python code. We can use these functions also as modules and import them
into other python scripts. This gives us a very modular structure for our complex code.
• OS python library is used to run system commands from python scripts like cd, mkdir,
chmod, cp, mv etc. There are other libraries as well for system tasks like sub process and
commands.
• Fabric is a python library used to run system commands on local and remote system. Most
of the python code is abratracted from us, we just call fabric functions for automating linux
tasks on local and remote system.
• Boto is a python system library to call, operate and manage AWS services from python.
Fabric documentation.
https://docs.fabric.io/
Boto Documentation
https://boto3.readthedocs.io/en/latest/