Programming in Python
S e c t i o n 0 2 | M o d u l e 0 3
© Caendra Inc. 2019
All Rights Reserved
Table of Contents
Module 03 | Programming in Python
3.1 About Python 3.6 Dictionaries
3.2 Variables & Types 3.7 Functions
3.3 Input / Output
3.8 Modules
3.4 Control Flow
3.9 Pentester Scripting
3.5 Lists
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.2
Learning Objectives
By the end of this module, you should have a
better understanding of:
• How to use python among operating systems
• Solid basics of python programming
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.3
Introduction
Welcome to the Python Programming Section!
In this section, we cover some important concepts about
Python.
You can find all the Python code samples used on the Resources drop-down menu of this
module.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.4
3.1
What is Python?
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.5
3.1 What is Python
Python is a powerful object-oriented programming
language, and it is:
• Cross-platform • Often used in scripting
• Free roles
• Interpreted: it runs directly • Easily usable in
from the source code (no conjunction with
need to compile it) components written in
other languages
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.6
3.1 What is Python
To start programming in Python, we need to download and
install it. You can do it at the following link:
http://www.Python.org/getit. If you use Kali Linux, please
skip this step, as Python is already installed in your OS.
http://www.python.org/getit PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.7
3.1 What is Python
Once installed we can start using Python in 2 different
ways: Basic interactive & IDLE (Python shell)
The basic interactive is a primitive
environment. If during the installation you
enabled the option ‘Add Python.exe to Path’,
you can run it by opening a command shell
and running the command ‘Python’.
IDLE combines an interactive interpreter with
code editing and debugging. You can run it by
pressing start and searching for ‘Python IDLE’.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.8
3.1 What is Python
When working interactively, the results of our code are displayed
after the >>> lines after you press the Enter key. Each time you
run a Python command, it runs immediately.
The above program is a “hello world” written in Python.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.9
3.1 What is Python
Installing Python in a Windows environment is a very simple
task. If you are going to use Kali Linux, Python is pre-
installed. Depending on the Kali release, different Python
versions may be installed. If you want to check your
version, open a console and type the following command:
python -V
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.10
3.1 What is Python
Moreover, if you want to use
Python idle, you need to
install the right packages.
You can do it typing the
following command:
apt-get install idle
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.11
3.1 What is Python
As shown in the below images, similar to Windows
systems, we can now run Python code by typing the
command python from the console. IDLE can be used by
typing the command idle-python2.7.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.12
3.1 What is Python
Since our next samples are based on Python 3.3.0 and
Python 3.4.2, we need to know how to install this version on
Linux systems.
The installation process is quite simple. In Kali Linux, we
can download Python 3.4.2 here:
http://www.Python.org/getit/
http://www.python.org/getit/ PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.13
3.1 What is Python
Now that we have downloaded the Python-3.4.2.tar.xz file,
open a console, move to the directory where the file resides
and run the following
commands:
tar xvf Python-3.4.2.tar.xz
cd Python-3.4.2/
./configure
make
make install
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.14
3.1 What is Python
Now we can run any Python version by typing the right
command.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.15
3.1 What is Python
Why Interactive?
The interactive prompt runs your code on the fly, but
remember that it does not save your code in a file. It is very
useful if you want to experiment and test short programs.
The immediate feedback of the interactive prompt is the
best way to start learning how Python works and it is the
easiest way to learn what a piece of code does without
running the whole program.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.16
3.1 What is Python
Using the interactive shell, we can see errors while we write our
code. In the below program we are trying to print a variable that
does not exist (f), and of course, the interpreter returns an error.
The last line of the
message shows the
exception detected,
while right above it we
can see the affected
statement.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.17
3.1 What is Python
As you can imagine, you can also create your program in a
non-interactive way. You can use any text editor to create it
or use the integrated editor in IDLE by clicking File->New
File.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.18
3.1 What is Python
Once your program is
complete, you must save
it using the .py
extension.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.19
3.1 What is Python
Now that your program is complete, you can run it from
within the IDLE window (Run->Run Module) or by using the
Windows command shell (python your_program.py).
Running the code from IDLE causes the code to run in the
Python Shell.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.20
3.1 What is Python
IMPORTANT NOTE!
Python differs from many other programming languages
because it uses whitespace and indentation to determine block
structures. In other words, Python specifies that several
statements are part of a single group by indenting them.
Indentation is a good practice that makes code easier to read.
While other programming languages (like C/C++/Java…) use
curly brackets ‘{}’ to begin and end instruction blocks, Python
uses indentation! PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.21
3.1 What is Python
The below code prints all the numbers from 0 to 9. As we
can see, C++ uses the { and } to delimit the body of the
while loop. In the Python screenshot, you can see that
Python does not use brackets to delimit a block, instead it
uses indentation.
Curly Brackets
delimit the block Indentation delimits the
block
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.22
3.1 What is Python
Here is another example that shows the importance of
indentation. The only difference between the two scripts is
the indentation at the print(n) statement.
Within while Outside while
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.23
3.1 What is Python
In the first case (left), the print statement is part of the
while block. If we run the script, print is executed 10 times.
In the second script (right), the print statement is outside
the while structure, and it is executed one time.
Outside while
Within while
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.24
3.2
Variables & Types
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.25
3.2 Variables & Types
Now that we know a few basic concepts of Python, we can
dive in.
In this section, we will see how to declare variables and
how we can assign values to them.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.26
3.2 Variables & Types
Unlike many other programming languages, in Python, there
is no variable type declaration or an end-of-line delimiter
(such as the ‘;’ delimiter).
x = 10
y = “Hello”
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.27
3.2 Variables & Types
x = 10
Here we see perfectly legal Python
y = “Hello”
code that creates a variable named ‘x’
and assigns the value 10 to that variable. The second
statement creates a new variable y and assigns the string
“Hello”.
As you can see, variables are created automatically when
they are first assigned a value.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.28
3.2 Variables & Types
We do not need to
declare the type of the
variable.
As shown in the above code, the same variable could first
refer to an integer value, and later be assigned a different
data type. Note that new assignments override any
previous assignment.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.29
3.2 Variables & Types
In the previous code, we Operator
= Assignment
have seen how easy it is + Addition
to declare numbers and - Subtraction
string variables. * Multiplication
/ Division (results in float)
You can manipulate // Division (results in truncation)
numbers with the ** Exponentiation
following operators: % Modulus
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.30
3.2 Variables & Types
Here are some examples that show how these operators
work.
Division with truncation
This assigns to y the previous y value plus 1.
Note this works on strings too.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.31
3.2 Variables & Types
Strings can be declared in many different ways.
You can use double quotes
(“ string ”), single quotes “ allow ‘single’ quotes ”
‘ allow “double” quotes ’
(‘ string ’), triple single ‘‘‘contain single and double quotes ’’’
quotes (‘‘‘ string ’’’) and “““ string that can
triple double quotes be written
in multiple lines ”””
(“““ string ”””).
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.32
3.2 Variables & Types
Strings have several operators (in, +, *) and methods that
allow you to work with the contents. You can find a
complete list at the following links.
Note that strings are immutable; meaning that methods and
operators will return new strings derived from the original.
• http://docs.Python.org/3.3/library/stdtypes.html#string-
methods
• http://docs.Python.org/3.3/library/text.html
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.33
3.2 Variables & Types
Here are some examples of these operators:
Strings are immutable
(x is still ‘Hello World’)
Assigns a new value to x.
Similar to previous assignment
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.34
3.2 Variables & Types
Moreover, note that strings can be accessed using indices:
First element of the string
Last element in the string
From element 0 to element 3
From element 4 to the end
From the beginning of the string to
the end of the string
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.35
3.3
Input / Output
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.36
3.3 Input / Output
We have already seen how to print messages and variables.
Let’s now look at how we can get user input and work with
it.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.37
3.3 Input / Output
While we are in interactive mode, we can print out the
variable value by typing its name; if we run a script in a non-
interactive mode, we have to use the print() function. The
below screenshots show the same program in interactive
(left) and non-interactive (right) mode.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.38
3.3 Input / Output
We know how to print output, but how can we get input from the
user?
To do it, we can use the input() function as follows:
user_input = input(“Message ”)
Where:
• user_input is the variable that will contain the user value
• Message is the text that will be displayed to the user right before
his input
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.39
3.3 Input / Output
Let’s look at an example!
This form automatically
inserts white spaces
between variables
The above code gets the user name and surname, and then
it prints out a welcome message.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.40
3.3 Input / Output
In the previous example, the user input is stored as a string.
The below code instead shows how to store the input as an
integer; this way we can perform arithmetical operations
with it.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.41
3.4
Control Flow
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.42
3.4 Control Flow
Python offers many different structures to control the
program execution and flow, such as conditional and loop
statements; let’s take a look at them in detail.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.43
3.4 Control Flow
IMPORTANT NOTE!
Python uses different ways to represent Boolean values. The
following are all interpreted as False:
• 0
• False
• None
• “” - Empty string
• [ ] - Empty list (we will see them later)
Everything else is considered as True.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.44
3.4 Control Flow
Operator
< Less than
<= Less than or equal
== Equal
The following table > Greater than
summarizes the comparison >= Greater than or equal
and logical operators that != Not equal
is / is not Object identity / negate
return True or False. in / not in Is inside / negate
And Logical AND
Or Logical OR
Not Logical NOT
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.45
3.4 Control Flow
The general form of the if-else statement is:
if expression:
statement
else:
statement
Where a statement may consist of a single statement, a
block of statements, or nothing (in the case of an empty
statement).
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.46
3.4 Control Flow
if expression:
statement The else clause is optional. If
else: expression evaluates to true, the
statement
statement or block that forms
the target of if is executed; otherwise, the statement or
block that is the target of else will be executed.
Please note the indentation above.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.47
3.4 Control Flow
The above program checks if the user value is greater than
or equal to 10. Depending on the value provided, the
program will print different messages, and the flag variable
is set to true or false.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.48
3.4 Control Flow
The if-else statement is
if expression_1:
very simple. statement_1
elif expression_2:
statement_2
If we want to evaluate elif expression_3:
several expressions we can statement_3
else:
use the if-elif-else statement_4
statements:
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.49
3.4 Control Flow
With the elif statement, we
can check several if expression_1:
expressions until we find statement_1
one that evaluates to true. elif expression_2:
statement_2
elif expression_3:
Once an expression is statement_3
evaluated to true, its else:
corresponding block will be statement_4
executed.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.50
3.4 Control Flow
This example shows how to use the elif statement.
Note that only one of the conditions is evaluated to true.
\n indicates a new line
\t indicates a tab
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.51
3.4 Control Flow
As in many other programming languages, if statements can be
nested:
if expression_1:
statement_1
if expression_2:
statement_2
if expression_3:
statement_3
else:
else_statement_of_first_if
We just need to be careful about indentation!
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.52
3.4 Control Flow
IMPORTANT NOTE!
In Python, there is no switch / case statement!
As we will see later on, this is something that can be easily
achieved using dictionary structures.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.53
3.4 Control Flow
In the C++ section, we already studied iteration statements,
also known as loops. They allow a set of instructions to be
executed repeatedly for a certain number of times or until a
certain condition is met.
Python offers two loops: while and for.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.54
3.4 Control Flow
Here we can see the general form of a while statement:
while condition:
statements_block
post_while_statements
As long as the condition is evaluated to True, the body of the
while (statement_block) is executed repeatedly. When the
condition is evaluated to False, the while loop terminates, and the
post_while_statements will be executed (the program
resumes on the statement following the while block).
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.55
3.4 Control Flow
5 => 5+4+3+2+1+0 => 15
1 => 1+0 => 1
The above program uses the while loop statement to sum
numbers from 0 to a given number (user input).
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.56
3.4 Control Flow
The following program uses
the while loop statement in
order to calculate the factorial
of a given number. The
program first gets the user
input and checks if it is 0.
If true, it does nothing (pass
statement) and then jumps to
the last statement; otherwise, it Note: comments do not need to be indented, but
calculates the factorial of the it makes the code more readable.
given number.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.57
3.4 Control Flow
Another loop statement is the for loop. Its general form is:
for item in sequence
for_statements
post_for_statements
Unlike many other programming languages, in Python, the
for loop does not increment and test a variable against a
condition on each iteration.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.58
3.4 Control Flow
It simply iterates through the
for item in sequence
values of a sequence object,
for_statements
such
post_for_statements as strings, lists or function like
range.
In other words, the body of the for loop will be executed for
each element in the sequence.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.59
3.4 Control Flow
Before seeing an example of the for loop, we’ll briefly
explain the range function. The range() function returns a
sequence of a given number; this is very useful if we want
to iterate with explicit indices.
For example, range(5) returns an iterable object that
contains values from 0 to 4.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.60
3.4 Control Flow
2 arguments 3 arguments
Note: In this example the list function is used to print all the elements within the range. We will see it later on.
We can also control the range function in this way:
• With 2 arguments ( range(x,y) ), we are saying which is the
starting number (x) of the sequence and which is the last
number (y) of the sequence.
• With 3 arguments ( range(x,y,z) ), we can also choose the
step value between each item in the sequence.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.61
3.4 Control Flow
The following program uses the for loop
with the range function in order to print all
the values that it finds during iteration.
As you can see, in the first loop, x is set to
be the first item in the sequence; in the
second loop, it is set to be the second item
of the sequence, and so on (no matter what
was its value before the loop).
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.62
3.4 Control Flow
Let’s say we want to write a program
that calculates the exponential value
(^2) of all the even numbers in the
range from 0 to a given number.
Here we can see a simple script that
does this.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.63
3.5
Lists
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.64
3.5 Lists
Python lists are similar to arrays in other programming
languages; they are ordered collections of any type of
object.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.65
3.5 Lists
The general form of a list is a comma-separated list of elements,
embraced in square brackets:
simple_list = [1,2,3,4,5]
list = [1,2,“els”,4,5,‘something’,[0,9]]
The above is a perfect legal list. Unlike arrays of other
programming languages, lists can contain objects of different
types. We do not need to fix its size, and moreover, unlike
Python’s strings, they are mutable, meaning that elements can be
modified by assignments.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.66
3.5 Lists
IMPORTANT NOTE!
simple_list = [“first”,2,“els”,4]
In almost every 0 1 2 3
programming
language, indices Index Element value
start from 0; this 0 first
1 2
applies to Python
2 els
as well. 3 4
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.67
3.5 Lists
The nested list ‘[6,7]’ is
considered as a single element
Elements can be modified or
new elements can be added
Slice notation can be used to
copy part of the list
Similar to Python strings, lists can be accessed by indices.
Moreover, since they are mutable, items can be modified
(this is not possible with strings).
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.68
3.5 Lists
The list y is appended as a single
element
List y is merged with x
Add an element before index 2
Python implements many functions that can be used to modify a list:
• append: append a new element to the target list
• extend: allows to add one list to another
• insert: add a new list element right before a specific index
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.69
3.5 Lists
Delete element with index 2
Delete the new element with index 2
Delete all the elements with index greater than or equal to 2
Similar to del method
While the previous methods can be used to add or edit list
elements, the del method can be used to delete list items or
slices. Note that once elements are deleted, indices are
automatically updated.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.70
3.5 Lists
Find an element with value 3, and if it exists
delete it
Only the first instance of 2 is removed
If the element does not exist, raise an exception
The remove method is quite different from the others. It does not
work with indices; instead, it looks for a given value within the list,
and if this exists, it removes the element. Note that only the first
instance of that value is removed.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.71
3.5 Lists
There are many other methods that can be used to
manipulate lists:
Method Description
list.pop(i) Removes the item at the given position
list.sort() Sorts a list ( they must be of the same type)
list.reverse() Reverses the order of the elements in the list
If you want to know more about them, take a look at the
following link.
http://docs.python.org/3.3/tutorial/datastructures.html#more-on-lists PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.72
3.6
Dictionaries
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.73
3.6 Dictionaries
Dictionaries, also known as mapping objects, are
something similar to associative arrays of other
programming languages.
While lists are indexed by numbers, dictionaries use keys
for indexing elements (keys are immutable types like
strings and numbers).
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.74
3.6 Dictionaries
The general form of a dictionary consists of one or more
“key:value” pairs embraced in curly brackets:
dictionary = {‘first’:‘one’, ‘second’:2}
Where the element on the left of the of the colon is the key,
and the element on the right is its associated value. As
much as lists, dictionaries can store objects of any type and
values are not implicitly ordered.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.75
3.6 Dictionaries
Create a dictionary
Add 1 to the value assigned to key “second”
Unlike lists, if the key does not exist, a new key:value pair is added at the beginning of the
dictionary
The above code shows some operations on dictionary elements.
As you can see, we can access an element like we did with lists,
but now we have to use keys instead of indices.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.76
3.6 Dictionaries
Many of the methods seen so far
are allowed on a dictionary.
Moreover, since in dictionaries we have keys and values, we have
some more methods.
• dictionary.values() returns all the values stored in the dictionary
• dictionary.keys() returns all the keys stored in the dictionary
• dictionary.items() returns all keys and values in the dictionary
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.77
3.6 Dictionaries
We can also check if a specific item exists using the following
two methods:
• key in dictionary
• get(key, message): if the key exists, returns the
associated value, otherwise prints the message
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.78
3.6 Dictionaries
Create a dictionary
Get the input from the user
Use the user input to
Check if the input exists in get and print the right
the dictionary otherwise value
print “Wrong input”
As we already stated, Python dictionaries can be used to create
something similar to a switch/case. The above code shows how we can
use dictionaries key:value pairs in order to associate a fixed message
to a key when the user input matches that key.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.79
3.7
Functions
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.80
3.7 Functions
A function is a group of statements that gets executed
when it is called (function call).
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.81
3.7 Functions
The general form of a function definition is:
def function_name(parameter1, parameter2,…):
function_statements
return expression
Where:
• def indicates a function definition
• function_name is the identifier of the function
• parameters is a comma-separated list of variables
• function_statements is the body of the function
• return exits a function and gives the execution back to the caller
Python functions body must be indented in order to delimit the start and the end of the function itself.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.82
3.7 Functions
*Note that functions must be
defined before they can be called
Define function
my_sum
Call function
my_sum and
store the value
returned in x
The program above shows how to define a function that
returns the sum of two numbers. Note that every function
should be documented.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.83
3.7 Functions
For this purpose, we can
use the triple-double
quote right after the
function definition in
order to explain what
that function does.
We can then call this description by typing
function_name.__doc__.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.84
3.7 Functions
Global x.
Local Variable z and f are local and
can only be used within the
Global
function
scope
One of the most important things when using functions is to
understand the scope of variables. In Python, each call to a
function creates a new local scope as well as all the assigned
names within a function that are local to that function.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.85
3.7 Functions
Variables x and y are local to the
function. Calling the function
Local with x parameter overrides the
value of the global x
Global x
Global
scope
The previous example is also useful to explain the variable scope. As you can see,
two variables x are used, but they have different values depending on their scope.
The first x is local to the function and can be used only within my_sum. Each change
made to this variable has no effect outside the function. The second x is global and
can be used in the entire program (within the single file).
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.86
3.7 Functions
With global Without global
statement statement
Global variables can be used within the function. To do that, we
need to insert the keyword global followed by the variable name.
For example, the above code shows how we can change the
value of a global variable from within a function. Calling the
function without the statement global x would always print 4.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.87
3.7 Functions
Parameters are usually passed
by position; this means that
when we call a function, the
parameters in the calling function are matched according to
their order.
So the number of parameters used by the caller and the
called function must be the same; otherwise, an exception
will be raised.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.88
3.7 Functions
In Python, we can change
this behavior passing
variables by name; this is
possible by using the name
of the corresponding
parameter.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.89
3.7 Functions
Another useful feature consists of assigning functions to
variables.
Once a variable refers to a function, it can be used in the
same way as the function.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.90
3.7 Functions
As shown in the Function definition
following code, Assign function a and b to
which is similar to dictionary values and use the
key to select them
the switch seen
before, this can be
Print a selection menu
very useful in
conjunction with Check if the user input is valid. If
dictionaries. true, get a value from the user,
then call the right function using
the dictionary (function_switch)
and print the result
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.91
3.7 Functions
The user chooses option 1 and types 5.
user = 1 x=5
function_switch[user](x) is then
function_switch[1](5)
function_switch[1] is a then
a(5) is called
Then result = function_switch[1](5) is then executed.
Since the value of function_switch[1] is a, the function a(5) is called, and the
result is stored in the variable result.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.92
3.8
Modules
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.93
3.8 Modules
A module is a file that contains source code. The main
purpose of modules is to group Python functions and
objects in order to organize larger projects. Note that in
addition to Python code, we can also import C++ object
files.
Let’s see then how to create a new module and how we can
use it.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.94
3.8 Modules
First, we need to create a new file and insert our code into
it. Let’s suppose we want to create a function that returns
the double of a number. Once we have our code, save the
file into the Python directory and name it “my_double.py”.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.95
3.8 Modules
We can use objects defined within the
imported module.
Print the documentation of the module and
the function
When a module name is typed in, Ctrl +
spacebar will print a menu with all the
objects of that module
Now we can run a new shell and import our module. To do it, let’s type the keyword
import followed by the name of our file (my_double). Once we import the module, if
no errors or warnings are raised, we can use objects defined in it by typing the
module name and the object name separated by a dot (my_double.some_variable).
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.96
3.8 Modules
In the previous example, we had to write the module name
each time we wanted to use an object. In order to directly
use an object, we can use the following syntax:
from module_name import object_name1, object_name2,…
Moreover, if we want to import all functions and objects
within the module, we can also use the following syntax:
from module_name import *
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.97
3.8 Modules
Below are some screenshots of the previous commands:
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.98
3.9
Scripting for
Pentesters
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.99
3.9 Scripting for Pentesters
Now that we have all the basic knowledge required to write
small Python programs, let’s look at some code examples
that can be useful to a Penetration Tester.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.100
3.9 Scripting for Pentesters
The following is a list of the Python programs we are
going to write:
• Network Sockets • HTTP Verbs
Enumerator
• Port Scanner
• Login brute force
• Backdoor
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.101
3.9.1. Network Sockets
The first program we are going to write will use sockets.
Network sockets are used in computer networks to
exchange data (packets) between two endpoints (from a
source to a destination).
If you want to know more about Python sockets, you can
use the following link:
http://docs.Python.org/3/library/socket.html
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.102
3.9.1. Network Sockets
What we are going to write is a program that binds itself to
a specific address and port and will listen for incoming TCP
communications (a server)
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.103
3.9.1. Network Sockets
The following code is a
working example of a server.
First, we need to import the
socket module and then get
the address and the port from
the user.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.104
3.9.1. Network Sockets
Here we create a new socket
using the default family
socket (AF_INET) that uses
TCP and the default socket
type connection-oriented
(SOCK_STREAM).
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.105
3.9.1. Network Sockets
The program will then print a
message showing the address
of the connected client and
then will start an infinite loop
in order to get and print all the
messages received from it.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.106
3.9.1. Network Sockets
Once the socket is configured, we
print a message saying that the
server is up. Then, we use the accept
function to accept incoming
connections. This function returns
two values:
• connection: is the socket object
we will use to send
and receive data
• address: it contains the client
address bound to the socket
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.107
3.9.1. Network Sockets
The bind function binds the socket
to the provided address and port,
while the listen function instructs
the socket to listen for an incoming
connection.
The argument 1 specifies the
maximum number of queued
connections.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.108
3.9.1. Network Sockets
SERVER
CLIENT
Above we can see the communications between the server
(our Python program) and a client (in this example netcat
running on another machine).
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.109
3.9.1. Network Sockets
In the previous example, we saw how easy it was to
EXERCISE!
create a server using the socket module.
Let’s practice with Python. Your task is to now use the
socket module to create a simple client that starts a
connection to the Python server and then sends a
message. This time, instead of using the bind and
listen function, we have to use the function named
connect.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.110
3.9.1. Network Sockets
Solution!
Please continue only if you have solved the exercise.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.111
3.9.1. Network Sockets
Here we see a simple CLIENT
example of a Python
client. We get the server
address and port from
the user, then we start the
connection (connect) and
send a message SERVER
(sendall).
Note that we need to
encode the message with
the encode() function.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.112
3.9.2. Port Scanner
In the next example, we are going to write a simple port
scanner.
The script takes an IP address and a port range and verifies
if the provided ports are open or not.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.113
3.9.2. Port Scanner
Similarly to the previous example, we have to import the
socket module. Instead of using the connect() function we
are going to use the connect_ex() function, which returns 0
if the operation succeeded; otherwise, it returns an error
code. This way we will know if the connection occurred or
not.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.114
3.9.2. Port Scanner
The script we are going to write will use a full three-way
handshake. Do you remember it?
You should have already studied it in the networking basics
section.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.115
3.9.2. Port Scanner
If you want to see what our Python code does while you
program, please consider running Wireshark in the
background. It can be a great way to ensure everything is
working properly.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.116
3.9.2. Port Scanner
This simple code works well
for our purpose. We first get
the IP address and the port
range to scan from the user.
Then in the for loop, the code
tries a connection to each
port in the range provided. If
the result of the connection is
0 the port is open; otherwise,
it is considered closed.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.117
3.9.2. Port Scanner
The image we see here is the
result of a scan performed with
our program against the target
192.168.1.131 on ports in the
range 20 to 35.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.118
3.9.3. Backdoor
We strongly believe that the best way to learn
EXERCISE!
something is by practicing it.
What we want you to build is a simple Python
backdoor (client and server) that allows you to:
• Get some system information (you decide)
• Get the content of a specific remote folder
Continue…
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.119
3.9.3. Backdoor
You can do so by using the following modules:
EXERCISE!
Sockets: http://docs.Python.org/3/library/socket.html
OS: http://docs.Python.org/3.3/library/os.html
Platform: http://docs.Python.org/3/library/platform.html
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.120
3.9.3. Backdoor
Solution!
Please continue only if you have solved the exercise.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.121
3.9.3. Backdoor
The following is a simple
example of a server backdoor.
The program simply binds itself
to a NIC and a specific port
(6666) and then waits for the
client commands. Depending
on the command received, it
will return specific information
to the client.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.122
3.9.3. Backdoor
The above is a possible
implementation of the client.
On the left, is the portion of the client code that starts the connection to
the server backdoor. On the right, are the operations that we can send
to the server.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.123
3.9.3. Backdoor
Here we can see how the backdoor
client looks like when we run it.
Once we provide the IP and port of
the server, we can issue the
commands we have introduced to
get system information and list the
content of a specific folder on the
victim machine.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.124
3.9.4. HTTP
The next program we are going to see will make use of the
module HTTP.client. For more information, here is the link
to the documentation:
http://docs.Python.org/3/library/http.client.html
You have already studied how to do this using netcat.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.125
3.9.4. HTTP
Now we want to build a Python program that, given an IP
address/hostname and port, verifies if the remote Web
Server has the HTTP method OPTIONS enabled.
If it does, it tries to enumerate all the other HTTP methods
allowed.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.126
3.9.4. HTTP
First, we need to import
the module named
http.client and then get
the IP address and port
of the webserver from
the user.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.127
3.9.4. HTTP
The code tries a connection
to the IP address provided
and will start an OPTIONS
request.
If the request succeeds, the
program will get the server
response header and will
extract all the HTTP
methods allowed.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.128
3.9.4. HTTP
The above images show what we get if a remote Web
Server has the OPTIONS method enabled.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.129
3.9.4. HTTP
EXERCISE
Now that you know how to send an HTTP request
and get a response, try to create a program that
verifies if a specific resource exists. You can do it
by sending a GET request and then check the
status code returned in the response using the
function named status().
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.130
3.9.4. HTTP
Solution!
Please continue only if you have solved the exercise.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.131
3.9.4. HTTP
Status code 200: The request has succeeded
Status code 404: Not Found
The above code simply sends a GET request to a specific URL.
Depending on the status code returned, it prints if the resource
exists or not.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.132
3.9.5. Login Brute Force
What we want you to build now is a small program that
EXERCISE
will test a list of common usernames and passwords
(taken from a file) against a web application login
form. You can do it using just two Python modules:
• http.client
• urllib.parse
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.133
3.9.5. Login Brute Force
Solution!
Please continue only if you have solved the exercise.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.134
3.9.5. Login Brute Force
In our case, the target web
application works as follows:
once we provide a username and 192.168.1.129/bruteforce_login/verify_login.php
a password, it verifies if the
provided credentials are correct
(verify_login.php). Valid credentials
If true, the web application
redirects us to welcome.php; Incorrect credentials
otherwise, it redirects us back to
login.php.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.135
3.9.6 Lab – Python-
assisted exploitation
Python-assisted
exploitation
Try to write your own
python tools in order to
speed up target
exploration.
*Labs are only available in Full or Elite Editions of the course. To upgrade, click HERE. To access, go to the course in
your members area and click the labs drop-down in the appropriate module line or to the virtual labs tabs on the
left navigation.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.136
References
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.137
References
This concludes our Python tutorial. If you want to dig deeper into
this beautiful programming language, here are some references
that you can use:
The Python Tutorial
http://docs.Python.org/3/tutorial/index.html
The Python Standard Library
http://docs.Python.org/3/library/index.html
Violent Python: A Cookbook for Hackers, Forensic Analysts, Penetration
Testers and Security Engineers
http://www.amazon.com/Violent-Python-Cookbook-Penetration-
Engineers/dp/1597499579/ref=sr_1_10?ie=UTF8&qid=1361544887&sr=8-10&keywords=python+programming
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.138
References
Black Hat Python
https://nostarch.com/blackhatpython
Python Code Samples Used
You can find all the Python code samples used on the Resources drop-down menu of this
module.
Python
http://www.Python.org/getit
The Python Standard Library: String Methods
http://docs.Python.org/3.3/library/stdtypes.html#string-methods
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.139
References
The Python Standard Library: Lists
http://docs.python.org/3.3/tutorial/datastructures.html#more-on-lists
The Python Standard Library: Sockets
http://docs.Python.org/3/library/socket.html
The Python Standard Library: OS
http://docs.Python.org/3.3/library/os.html
The Python Standard Library: Platform
http://docs.Python.org/3/library/platform.html
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.140
References
http.client
http://docs.Python.org/3/library/http.client.html
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.141
Labs
Python-assisted exploitation
Try to write your own python tools in order to speed up target exploration.
*Labs are only available in Full or Elite Editions of the course. To upgrade, click HERE. To access, go to the course in your members area and
click the labs drop-down in the appropriate module line or to the virtual labs tabs on the left navigation.
PTSv4: Section 2, Module 3 - Caendra Inc. © 2019 | p.142