This presentation contains basics of Python language for anyone novice to start with. Towards the end there is a brute force python script in Kali Linux.
2. Contents
Data Types
• Lists
• Tuple
• Strings
Creating and reading files
Creating functions
Lambda
Loops
• For
• While
Conditional statement: If, Else, Elif
Modules
• sys
• os
• smtplib
Brute force script
3.
4. Overview
• Knowledge of a scripting language can save you a lot of time while
dealing with redundant tasks.
• Python is the go-to language, especially if you don’t have a coding
background: as its syntax are not too complicated and there are a lot
of modules for complex situations.
• This talk will touch on some basics about python and then we will
explore how python can be utilized in network security.
5. Why learn a scripting language?
• One can never always rely on automated tools.
• Writing a tool for something gives you a better understanding of
the topic.
Why “Python” for security professionals?
For security professionals, Python can be used for but not limited to:
• Penetration Testing
• Information gathering
• Scripting tools
• Automating stuff
• Forensics
8. How to run a Python code?
• Directly from the CLI
• Directly from a Python interpreter
• With the code saved in a file.py
Indentation
• For loops, conditional statements, functions, and others indentation is required.
• Some people use spaces and some use tabs.
Python help() function
It’s a built-in function, very useful for the beginners.
e.g. To check help menu for type() function: help(type)
9. Data Types
• Numbers
• Integers: 2, 5, 10, etc.
• Floats: 2.3, 4.65, etc.
• Strings
• “Strings are basically just a bunch of words.”
• Lists
• [‘hi’, ‘24’, ‘86’]
• Tuples
• (‘hello’,)
• (‘hello’, ‘1’, ‘54’)
• Dictionaries
• Key-value pairs
• picnicItems = {'cups':'4', 'apples':'3'}
The type() function can be used to check the data type of a given variable or object.
10. Python Lists
A list is a value that contains multiple values in an ordered sequence. e.g. spam = [‘eggs’, ‘bat’, ‘cat’, ‘mat’]
Few of many operations on a List:
Slicing:
spam[1:3] >> [‘bat’, ‘cat’]
Changing items:
spam[0] = ‘meat’ >> [‘meat’, ‘bat’, ‘cat’, ‘mat’]
Removing items:
del spam[2] >> [‘meat’, ‘bat’, ‘mat’]
Methods
• A method is the same thing as a function, except it is “called on” a value.
• The method part comes after the value, separated by a period.
• Each data type has its own set of methods, for Lists: index(), append(), remove(), insert(2, ‘rat’)
e.g. spam.index(‘bat’) >> 1
11. Python Tuple
• Tuple data type is almost identical to List data type with following two
differences:
• tuple uses () and not []
• tuples are immutable like strings (and not mutable like List data type)
• Converting list to tuple and tuple to list:
• It's simple as passing the list/tuple to the function list()/tuple()
12. Python Strings
• You can specify multi-line strings using triple quotes.
• Strings are Immutable, meaning: once you have created a string, you cannot change it.
Manipulation of Strings
Slicing
Format Method:
age=20
Name=Samar
print(‘{0} was {1} years old when he wrote the book.’).format(name, age) >> Samar was 20 years old when he wrote this
book.
join()
', '.join(['cats', 'rats', 'bats']) # you can pass anything as the delimiter.
'cats, rats, bats’
split()
'My name is Simon'.split()
['My', 'name', 'is', 'Simon']
13. Creating and Reading Files
The ability to create and read files in Python allows you to create
reports from your tools’ output and read input files to parse.
file = open(‘test.txt’, ‘w’) #creating a file
file.write(‘Hello world!’)
file.close()
file = open(‘test.txt’, ‘r’) #opening an existing file
file.readlines()
14. Creating functions
• Whenever you need to repeat a block of code, functions are helpful.
• The value that a function call evaluates to is called the return value of the function.
• if you use a return statement without a value (that is, just the return keyword by itself), then None is
returned.
• Syntax:
def function_name(list_of_arguments):
Line 1
……
Line n
return something
def CheckPortNumber(port):
if port > 65535 or port < 0:
return False
else:
return True
15. Lambda
These expressions allow us to create “anonymous” functions that are similar to the standard function definition.
It is considered to be one of the most useful tools in Python since it allows us to create ad-hoc functions.
def square(num):
return num**2
square(7)
Let’s re-write the above function with lambda expression:
square = lambda num: num**2
Consider another example: Print reverse of a string
reverse = lambda s: s[::-1]
reverse(“Anonymous”)
16. Python Controls – For Loop
We can use the range() function to specify the number of times we want the for loop to
execute.
for letter in range(0,2):
for lett in range(3):
print(‘Cyber’)
print(‘Security’)
p_list = [21, 22, 25, 80]
for port in p_list:
print(‘This is port: ’, port)
17. Python Controls – While Loop
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
i=0
while i<6:
i += 1
if i==3:
continue
print(i)
19. Exception handling
When you will write your own Python tools, you will come across some conditions when errors occur like:
• Can’t connect to the host
• Syntax error
• No data is returned from a particular function
To handle these error, you can use Try/Except loop in Python.
try:
a=0/0
except:
print('Exception happened')
else:
print('no Exception
happened')
finally:
print('Cleanup code')
20. Python Modules
Modules in Python are simply any file containing Python statements.
They extend the functionality of your Python scripts.
There are many built-in modules and third party modules developed by the community.
To use a module:
• import module
• import module1, module2, moduleN
• import module as newname
• from module import *
• from module import <specific>
21. Python “sys” Module
• The sys module provides information about constants, functions and methods of the Python interpreter.
• sys.argv returns a list of command line arguments passed to a Python script. The item at index 0 in this list is
always the name of the script.
• The rest of the arguments are stored at the subsequent indices.
# Check python path and count them
import sys
print("path has", len(sys.path),"members")
print("The members are:")
for member in sys.path:
print(member)
#Print all imported modules
print(sys.modules.keys())
#Print the platform type
print(sys.platform)
#Check the python working version
print(sys.version)
22. Python “os” Module
• This module provides a way of using operating system dependent functionality with Python.
• The ability to run OS commands from a Python script can be very handy and can help with a number of
automation use cases.
#Check platform name (UNIX/LINUX = posix, Windows=nt)
os.name
#Print the current working directory
os.getcwd()
#Joining the paths
os.path.join(‘aditya’,’py_scripts)
#Run a shell command
os.system("ping -c 127.0.0.1")
23. Module ‘smtplib’
Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending e-mail and routing e-mail
between mail servers.
smtplib module defines an SMTP client session object that can be used to send mail to any Internet
machine with an SMTP listener daemon.