Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Practical Web Penetration Testing

You're reading from   Practical Web Penetration Testing Secure web applications using Burp Suite, Nmap, Metasploit, and more

Arrow left icon
Product type Paperback
Published in Jun 2018
Publisher Packt
ISBN-13 9781788624039
Length 294 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
 Khawaja Khawaja
Author Profile Icon Khawaja
Khawaja
Arrow right icon
View More author details
Toc

Table of Contents (22) Chapters Close

Title Page
Packt Upsell
Contributors
Preface
1. Building a Vulnerable Web Application Lab 2. Kali Linux Installation FREE CHAPTER 3. Delving Deep into the Usage of Kali Linux 4. All About Using Burp Suite 5. Understanding Web Application Vulnerabilities 6. Application Security Pre-Engagement 7. Application Threat Modeling 8. Source Code Review 9. Network Penetration Testing 10. Web Intrusion Tests 11. Pentest Automation Using Python 1. Nmap Cheat Sheet 2. Metasploit Cheat Sheet 3. Netcat Cheat Sheet 4. Networking Reference Section 5. Python Quick Reference 6. Other Books You May Enjoy Index

Quick Python language overview


It's time to start learning Python. I included this section in the book for two reasons. The first is that I want you to use it as a reference for when you develop your Python scripts in the future. The second reason is that I want to refresh your memory about this amazing programming language. It is important to note that I can't fit all the information about this programming language in an appendix, so I will include the most important elements of Python that will help you to achieve the most results in your career. You can enjoy learning and experimenting with the following examples using your Terminal window's Python interpreter—just type Python in your terminal window and you're ready to go.

Basics of Python

In this section, I will list all the basic operations that you need to be aware of when using the Python language:

  • To run a Python file, execute the following in your Terminal window:
$python [the_python_file_name.py]

   You can also use the following:

$./[the_python_file_name.py] 
  • Before executing the preceding command, you will need to give it the permission to execute:
$chmod +x [the_python_file_name.py]
  • To add comments to your code in Python, use the following syntaxes:
    • For a one-line comment use the # character, and use """ for a multiple-line comment :
# Comment one line

""" the three double quotes can be used
for multiple lines comments"""
  • To organize your blocks in Python, remember to press Tab to insert a new block section underneath the semicolon character:
    • In this example, we must create a new block underneath the if statement (exactly after the :character)
if x == 1:
x = x + 1
print 'Success'
  • If you want to go to a new line, use the backslash character, except for [], {}, or (). For example:
    • To combine three reports together, use the following:
report_results = nmap_report + \
theharvester_report + \
metasploit_report
    • To write a list of long IP addresses, use the following:
ips = ['192.168.0.1',192.168.0.10','192.168.0.99',
192.168.0.100]
  • To import other external libraries to use their functionalities, use the import keyword:
# import the os library to allow us to create a new directory
import os
#create a test directory
os.mkdir('Test')
  • To print a message to the console output, use the print function:
print 'The application has finished execution'
  • To accept user input from the Terminal window, use the raw_input function:
ip_address = raw_input('IP:')
print ip_address
  • Null objects in Python are represented by the None keyword:
if results is None:
  print ('Empty results')

Operators

There are so many types of operators that exist in the Python programming language. What is an operator? A simple example is the == operator, which is used by the if condition statement (for example, ifx==1). In general, operators come under the following categories:

Arithmetic calculation operators

Operator

Description

Example

+

Adds values

x + y + z = 5

- 

Subtracts values

num1 – num2 = 3

* 

Multiplies values

x * y = 9

/ 

Divides the left operand by the right operand

b / a = 3

%

Divides the left operand by the right operand and returns the remainder

x % a = 0

** 

Performs an exponential(power) calculation on operators

a**b =9 

Assignment operators

Operator

Description

Example

=

Assigns values

x=y

+= 

Adds the right operand to the left operand and assigns the result to the left operand

x +=y (same as x = x+y)

-= 

Subtracts the right operand from the left operand and assigns the result to the left operand

y -=x (same as y=y-x)

*= 

Multiplies the right operand by the left operand and assigns the result to the left operand

x *= a (same as x = x * a)

/= 

Divides the left operand by the right operand and assigns the result to the left operand

x /= a (same as x = x / ax

%= 

Performs a modulus on operators and assigns the result to the left operand

x %= a (same as x = x % a)

**= 

Performs an exponential (power) calculation on operators and assigns the result to the left operand

x **= a (same as x = x ** a)

Comparison operators 

Operator

Description

Example

==

If the two operands are equal, then the condition becomes true

x==y

!= or <>

If the two operands are not equal, then the condition becomes true

x!=y

>

If the left operand is greater than the value of the right operand, then the condition becomes true

x>y

<

If the left operand is less than the value of the right operand, then the condition becomes true

x<y

>=

If the left operand is greater than or equal to the value of the right operand, then the condition becomes true

x>=y

<=

If the value of the left operand is less than or equal to the value of the right operand, then the condition becomes true

x<= y

Membership and identity operators

Operator

Description

Example

in

Evaluates to true if it is a variable in the specified sequence

if 'tcp' in results:

not in

Evaluates to false if it is a variable in the specified sequence

if not 'http' in results:

is

Evaluates to true if the variables on either side of the operator are equal

 if results is None:

is not

Evaluates to true if the variables on either side of the operator are not equal

if results is not None:

Binary operators

Operator

Description

Example

& 

AND operator checks whether the result exists in both operands

1&1 = 1 

|

OR operator checks whether the result exists in either operand

0|1=1

^

XOR operator checks whether the result exists in one operand but not both

0^1=1

~

NOT operator refers to the opposite bit

~0=1

 

Making an if decision

Operator

Description

Example

if

Makes a decision based on the operands

if service == 80: print 'HTTP'

if-else

Takes a different action after an if decision

if service == 80:

    print 'HTTP'

else:

    print 'Not HTTP'

if-elif

Makes multiple sequential decisions

if service == 80:

    print 'HTTP'

elif service == 443:

    print 'TLS'

else:

    print 'Not HTTP or TLS'

Variables

Variables are used in Python and in other programming languages to store temporary values in memory in order to reuse them in multiple places in the source code.

We have various types of variables in Python, as shown in the following list:

  • Strings
  • Numbers
  • Lists
  • Dictionaries
  • Tuples

At any stage in your source code, you can cast from one variable to another using the following type casting syntaxes:

# A string type port number
port_number = "80"

# An integer, which holds the number of hosts
host_count = 254

# Convert port number into integer type
int(port_number)

# Convert port number into a float type with decimals
float(port_number)

# Convert the number of host into a string
str(host_count)

Strings

Use the string variable type when you want to store a set of characters into that variable:

  • You can use the string variable type as shown in the following example:
ip_address = '10.0.0.1'
# Or you can use double quotes:
ip_address= "10.0.0.1"
#Multiple lines, using triple double quotes/single quotes
welcome_message = """ Hello there, welcome to our powerful intelligent
                        script, you will be amazed!"""
  • To concatenate two string variables together, use the + sign:
device_name = 'Cisco Router 2911'
ip_address = '10.0.1.1'
host = device_name + ":" + ip_address
  • To format a string using the % operator, do the following:
ip_address = '10.0.1.1'
host = "router IP address is : %s" % ip_address
  • You can use the following formatters:
    • %s: String
    • %d: Integer number
    • %f: Float number
    • %x: Hexadecimal number
Escape String Characters

Backslash notation

Hexadecimal character

Description

\a

0x07

Bell or alert

\b

0x08

Backspace

\e

0x1b

Escape

\f

0x0c

Formfeed

\n

0x0a

Newline

\r

0x0d

Carriage return

\s

0x20

Space

\t

0x09

Tab

  • To remove trailing and leading white spaces from a string, include a white space before the Welcomeand a leading space after thePython:
message = " Welcome To Python "
message = message.strip()
  • To get the length of a string, do the following:
ip_address = '10.0.1.1'
string_length = len(ip_address)
  • To split a string and return the value in a list, do the following:
ips= "10.0.0.1,10.0.0.2"
ips_splitted = ips.split(',')
print ips_splitted[0]

Numbers

The following is a list of the most common numerical types that Python supports:

  • int: These are sometimes called integers, and they are positive or negative whole numbers with no decimal point (for example, 11).
  • long (long integers): These are integers of unlimited size, written like integers and followed by an uppercase or lowercase L (for example, 788739888999L).
  • float (floating points): These represent real numbers, and are written with a decimal point (99.9999). Floats are sometimes used in scientific notation, with E or e indicating the power of 10 (2e2 = 2 x 102).
  • To get the maximum or minimum of two numbers, do the following:
num1 = max(2,8)
num2=min(2,8)
  • To generate a random number from a range, do the following:
# Generate a Random number from 10 to 100 and with 1 increment at a time (10,11,12,13...100)
import random
rand = random.randrange(10,100,1)

Lists

A list is a collection of items (for example, strings, numbers, objects, and so on). In other programming languages, it's called an array. Now, should you hear that word in the future, you'll know that it means a list in Python:

  • Here is an example of a list:
ips = ['192.1.1.1','192.1.1.254']
  • To add a new item to the list, use the append function:
ips = ['192.1.1.1','192.1.1.254']
# To add a third item to the list
ips.append('192.1.1.2')
print ips
  • To access each item in the list, use its index number. For example:
ips = ['192.1.1.1','192.1.1.254']
# Print the first IP address
print ips[0]
  • To change an item in a list, just use its index and assign it a new value. For example:
ips = ['192.1.1.1','192.1.1.254']
# Assign the first item a new value
ips[0] = 192.168.1.1
  • To delete an item from the list, do the following:
ips = ['192.1.1.1','192.1.1.254']
# We will delete the first IP address:
del ips[0]
print ips
  • To get the length of a list, use the len function. For example:
ips = ['192.1.1.1','192.1.1.254']
# Print the length of the ips list which is 2 in this case:
print len(ips)

Tuples

Tuples are similar to lists, but they're read only. I rarely use them, but they exist in Python, and you need to be aware of their existence:

  • To declare a tuple variable, do the following:
ips = ('1.1.1.1','2.2.2.2')
  • To access an item in a tuple, use its index number. For example:
ips = ('1.1.1.1','2.2.2.2')
# Print the first IP address
ips[0]
  • To get the length of a tuple, use the len function. For example:
ips = ('1.1.1.1','2.2.2.2')
# Print the length of the ips list which is 2 in this case:
print len(ips)

Dictionary

A dictionary is a list of items with key and value pairs. The best way to describe it is by using examples. Let's start:

  • To declare a key–value pair of the host and IP, enter the following (for example):
hosts_dictionary = { 'Srv-001':'10.0.0.100', 'Srv-002':'10.0.0.100'}
  • To add a new item to a dictionary, do the following:
hosts_dictionary = { 'Srv-001':'10.0.0.100', 'Srv-002':'10.0.0.101'}
hosts_dictionary['Srv-003'] = '10.0.0.103'
print hosts_dictionary
  • To update an existing item in a dictionary, do the following:
hosts_dictionary = { 'Srv-001':'10.0.0.100', 'Srv-002':'10.0.0.101'}
hosts_dictionary['Srv-002'] = '10.0.0.122'
print hosts_dictionary
  • To delete an existing item in a dictionary, do the following:
hosts_dictionary = { 'Srv-001':'10.0.0.100', 'Srv-002':'10.0.0.101'}
del hosts_dictionary['Srv-002']
print hosts_dictionary
  • To iterate through a dictionary, do the following:
hosts_dictionary = { 'Srv-001':'10.0.0.100', 'Srv-002':'10.0.0.101'}
for host,ip in hosts_dictionary.items(): print "host:%s , IP: %s" % (host,ip)

Miscellaneous

  • To create a function, use the def keyword, followed by the function name, some optional variables, and the : character at the end.  For example:
def addition(x,y): 
    return x + y
  • To create a for loop, do the following:
ips = ['192.1.1.1','192.1.1.254']

for ip in ips:
    print ip
  • The following is a sample custom class object in Python:
# class name
class Host:
    #class constructor
    def __init__(self,name):
        self.name = name
    def print_host(self):
        print self.name

#let's call it from somewhere else
h = Host('SRV-001')
h.print_host()
  • To manage errors using exceptions in Python, do the following:
try:
    [put your code here]
except Exception, e:
    exception_message = str(e)
    print("Error: " + exception_message)
  • To open and read a text file, do the following:
f=open('/root/dic.txt',r)
for txt in f:
    print txt
f.close()
  • To write to a file, do the following:
f=open('ips.txt',a)
f.write('192.168.0.0\n')
f.close()
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime
Visually different images