Python language essentials
In this section we will go through the idea of variables, strings, data types, networking, and exception handling. For an experienced programmer, this section will be just a summary of what you already know about Python.
Variables and types
Python is brilliant in case of variables. Variables point to data stored in a memory location. This memory location may contain different values, such as integers, real numbers, Booleans, strings, lists, and dictionaries.
Python interprets and declares variables when you set some value to this variable. For example, if we set a = 1 and b = 2.
Then we print the sum of these two variables with:
print (a+b)
The result will be 3
as Python will figure out that both a and b are numbers.
However, if we had assigned a = "1" and b = "2". Then the output will be 12
, since both a and b will be considered as strings. Here, we do not have to declare variables or their type before using them as each variable is an object. The type()
method can be used to get the variable type.
Strings
As with any other programming language, strings are one of the important things in Python. They are immutable. So, they cannot be changed once defined. There are many Python methods which can modify strings. They do nothing to the original one, but create a copy and return after modifications. Strings can be delimited with single quotes, double quotes, or in case of multiple lines, we can use triple quotes syntax. We can use the \
character to escape additional quotes which come inside a string.
Commonly used string methods are as follows:
string.count('x')
: This returns the number of occurrences of'x'
in the stringstring.find('x')
: This returns the position of character'x'
in the stringstring.lower()
: This converts the string into lowercasestring.upper()
: This converts the string into uppercasestring.replace('a', 'b')
: This replaces alla
withb
in the string
Also, we can get the number of characters, including white spaces, in a string with the len()
method:
#!/usr/bin/python a = "Python" b = "Python\n" c = "Python " print len(a) print len(b) print len(c)
You can read more about the string function here: https://docs.python.org/2/library/string.html.
Lists
Lists allow us to store more than one variable inside it and provide a better method for sorting arrays of objects in Python. They also have methods which help to manipulate the values inside them:
list = [1,2,3,4,5,6,7,8] print (list[1])
This will print 2
, as Python index starts from 0. To print out the whole list, use the following code:
list = [1,2,3,4,5,6,7,8] for x in list: print (x)
This will loop through all elements and print them.
Useful list methods are as follows:
.append(value)
: This appends an element at the end of the list.count('x')
: This gets the number of'x'
in the list.index('x')
: This returns the index of'x'
in the list.insert('y','x')
: This inserts'x'
at location'y'
.pop()
: This returns the last element and also removes it from the list.remove('x')
: This removes first'x'
from the list.reverse()
: This reverses the elements in the list.sort()
: This sorts the list alphabetically in ascending order, or numerical in ascending order
Dictionaries
A Python dictionary is a storage method for key:value pairs. Python dictionaries are enclosed in curly braces, {}
. For example:
dictionary = {'item1': 10, 'item2': 20} print(dictionary['item2'])
This will output 20
. We cannot create multiple values with the same key. This will overwrite the previous value of the duplicate keys. Operations on dictionaries are unique. Slicing is not supported in dictionaries.
We can combine two distinct dictionaries to one by using the update method. Also, the update method will merge existing elements if they conflict:
a = {'apples': 1, 'mango': 2, 'orange': 3} b = {'orange': 4, 'lemons': 2, 'grapes ': 4} a.update(b) Print a
This will return the following:
{'mango': 2, 'apples': 1, 'lemons': 2, 'grapes ': 4, 'orange': 4}
To delete elements from a dictionary we can use the del
method:
del a['mango'] print a
This will return the following:
{'apples': 1, 'lemons': 2, 'grapes ': 4, 'orange': 4}
Networking
Sockets are the basic blocks behind all network communications by a computer. All network communications go through a socket. So, sockets are the virtual endpoints of any communication channel that takes place between two applications which may reside on the same or different computers.
The socket module in Python provides us a better way to create network connections with Python. So to make use of this module, we have to import this in our script:
import socket socket.setdefaulttimeout(3) newSocket = socket.socket() newSocket.connect(("localhost",22)) response = newSocket.recv(1024) print response
This script will get the response header from the server. We will discuss more about networking in our later chapters.
Handling exceptions
Even though we wrote syntactically correct scripts, there will be some errors while executing them. So, we have to handle the errors properly. The simplest way to handle exceptions in Python is by using try-except
:
Try to divide a number by zero in your Python interpreter:
>>> 10/0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: integer division or modulo by zero
So, we can rewrite this script with try-except
blocks:
try: answer = 10/0 except ZeroDivisionError, e: answer = e print answer
This will return the error integer division or modulo by zero
.
Tip
Downloading the example code
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
- Log in or register to our website using your e-mail address and password.
- Hover the mouse pointer on the SUPPORT tab at the top.
- Click on Code Downloads & Errata.
- Enter the name of the book in the Search box.
- Select the book for which you're looking to download the code files.
- Choose from the drop-down menu where you purchased this book from.
- Click on Code Download.
You can also download the code files by clicking on the Code Files
button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
- WinRAR / 7-Zip for Windows
- Zipeg / iZip / UnRarX for Mac
- 7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Effective-Python-Penetration-Testing. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!