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 :
- For a one-line comment use the
# 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)
- In this example, we must create a new block underneath the
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, if
x==1
). In general, operators come under the following categories:
Arithmetic calculation operators
Operator | Description | Example |
| Adds values |
|
| Subtracts values |
|
| Multiplies values |
|
| Divides the left operand by the right operand |
|
| Divides the left operand by the right operand and returns the remainder |
|
| Performs an exponential(power) calculation on operators |
|
Assignment operators
Operator | Description | Example |
| Assigns values |
|
| Adds the right operand to the left operand and assigns the result to the left operand |
|
| Subtracts the right operand from the left operand and assigns the result to the left operand |
|
| Multiplies the right operand by the left operand and assigns the result to the left operand |
|
| Divides the left operand by the right operand and assigns the result to the left operand |
|
| Performs a modulus on operators and assigns the result to the left operand |
|
| Performs an exponential (power) calculation on operators and assigns the result to the left operand |
|
Comparison operators
Operator | Description | Example |
| If the two operands are equal, then the condition becomes true |
|
| If the two operands are not equal, then the condition becomes true |
|
| If the left operand is greater than the value of the right operand, then the condition becomes true |
|
| If the left operand is less than the value of the right operand, then the condition becomes true |
|
| If the left operand is greater than or equal to the value of the right operand, then the condition becomes true |
|
| If the value of the left operand is less than or equal to the value of the right operand, then the condition becomes true |
|
Membership and identity operators
Operator | Description | Example |
| Evaluates to true if it is a variable in the specified sequence |
|
| Evaluates to false if it is a variable in the specified sequence |
|
| Evaluates to true if the variables on either side of the operator are equal | |
| Evaluates to true if the variables on either side of the operator are not equal |
|
Binary operators
Operator | Description | Example |
| AND operator checks whether the result exists in both operands |
|
| OR operator checks whether the result exists in either operand |
|
| XOR operator checks whether the result exists in one operand but not both |
|
| NOT operator refers to the opposite bit |
|
Making an if decision
Operator | Description | Example |
| Makes a decision based on the operands |
|
| Takes a different action after an |
|
| Makes multiple sequential decisions |
|
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 |
| 0x07 | Bell or alert |
| 0x08 | Backspace |
| 0x1b | Escape |
| 0x0c | Formfeed |
| 0x0a | Newline |
| 0x0d | Carriage return |
| 0x20 | Space |
| 0x09 | Tab |
- To remove trailing and leading white spaces from a string, include a white space before the
Welcome
and 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()