SlideShare a Scribd company logo
Python
for
Security Professionals
Aditya Shankar
Security Analyst
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
Python for Security Professionals
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.
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
Python for Security Professionals
Let’s get started with the basics of Python
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)
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.
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
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()
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']
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()
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
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”)
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)
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)
Conditional statements: IF, ELSE, and ELIF
p_list = [21,22,25,80]
if p_list[0] == 21:
print("FTP service")
elif p_list == 22:
print("SSH service")
else:
print("Unknown Service")
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')
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>
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)
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")
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.
Python for Security Professionals
Python script for brute forcing Gmail accounts
Thank You.

More Related Content

PDF
Python made easy
PPTX
Programming in Python
PPTX
Tuples, Dicts and Exception Handling
PPTX
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PPT
Intro to Functions Python
PPTX
Intro to Python Programming Language
PPTX
Python Tutorial Part 1
Python made easy
Programming in Python
Tuples, Dicts and Exception Handling
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Intro to Functions Python
Intro to Python Programming Language
Python Tutorial Part 1

What's hot (20)

PPTX
Testing in Python: doctest and unittest (Updated)
PPTX
Testing in Python: doctest and unittest
PPTX
Python basics
PPTX
Fundamentals of Python Programming
PPTX
Python 3 Programming Language
PDF
4. python functions
PPTX
Functions, List and String methods
PDF
Introduction To Programming with Python
PPTX
Java I/O
PPTX
Basic Python Programming: Part 01 and Part 02
PPTX
Python ppt
PDF
Python basic
PPTX
Python 101: Python for Absolute Beginners (PyTexas 2014)
PDF
What is Python?
PDF
Python Basics
PPTX
Python for Beginners(v1)
PDF
Introduction to Python for Bioinformatics
PPTX
Python Seminar PPT
PPTX
Introduction to Python Part-1
PDF
Python Tutorial
Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest
Python basics
Fundamentals of Python Programming
Python 3 Programming Language
4. python functions
Functions, List and String methods
Introduction To Programming with Python
Java I/O
Basic Python Programming: Part 01 and Part 02
Python ppt
Python basic
Python 101: Python for Absolute Beginners (PyTexas 2014)
What is Python?
Python Basics
Python for Beginners(v1)
Introduction to Python for Bioinformatics
Python Seminar PPT
Introduction to Python Part-1
Python Tutorial
Ad

Similar to Python for Security Professionals (20)

PDF
web programming UNIT VIII python by Bhavsingh Maloth
PDF
Tutorial on-python-programming
PPT
Introduction to python
PPTX
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
PPTX
Docketrun's Python Course for beginners.pptx
KEY
Programming with Python - Week 3
PPTX
FILE AND OBJECT<,ITS PROPERTIES IN PYTHON
PPT
Python ppt
PDF
Python (3).pdf
PPT
1B-Introduction_to_python.ppt
PPT
Python Programming Basic , introductions
PPTX
INTRODUCTION TO PYTHON.pptx
PDF
W-334535VBE242 Using Python Libraries.pdf
PPT
01-Python-Basics.ppt
PPT
ENGLISH PYTHON.ppt
PDF
Python cheat-sheet
PPTX
manish python.pptx
PPT
python1.ppt
PPT
Python Basics
PPT
python1.ppt
web programming UNIT VIII python by Bhavsingh Maloth
Tutorial on-python-programming
Introduction to python
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
Docketrun's Python Course for beginners.pptx
Programming with Python - Week 3
FILE AND OBJECT<,ITS PROPERTIES IN PYTHON
Python ppt
Python (3).pdf
1B-Introduction_to_python.ppt
Python Programming Basic , introductions
INTRODUCTION TO PYTHON.pptx
W-334535VBE242 Using Python Libraries.pdf
01-Python-Basics.ppt
ENGLISH PYTHON.ppt
Python cheat-sheet
manish python.pptx
python1.ppt
Python Basics
python1.ppt
Ad

Recently uploaded (20)

PDF
Architecture types and enterprise applications.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
Tartificialntelligence_presentation.pptx
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PPTX
OMC Textile Division Presentation 2021.pptx
PDF
2021 HotChips TSMC Packaging Technologies for Chiplets and 3D_0819 publish_pu...
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PDF
DP Operators-handbook-extract for the Mautical Institute
PPTX
The various Industrial Revolutions .pptx
PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
A novel scalable deep ensemble learning framework for big data classification...
PDF
A contest of sentiment analysis: k-nearest neighbor versus neural network
PPTX
TLE Review Electricity (Electricity).pptx
PPT
Module 1.ppt Iot fundamentals and Architecture
PPT
What is a Computer? Input Devices /output devices
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
Architecture types and enterprise applications.pdf
Programs and apps: productivity, graphics, security and other tools
Tartificialntelligence_presentation.pptx
gpt5_lecture_notes_comprehensive_20250812015547.pdf
NewMind AI Weekly Chronicles - August'25-Week II
OMC Textile Division Presentation 2021.pptx
2021 HotChips TSMC Packaging Technologies for Chiplets and 3D_0819 publish_pu...
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
Univ-Connecticut-ChatGPT-Presentaion.pdf
DP Operators-handbook-extract for the Mautical Institute
The various Industrial Revolutions .pptx
A comparative study of natural language inference in Swahili using monolingua...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
A novel scalable deep ensemble learning framework for big data classification...
A contest of sentiment analysis: k-nearest neighbor versus neural network
TLE Review Electricity (Electricity).pptx
Module 1.ppt Iot fundamentals and Architecture
What is a Computer? Input Devices /output devices
Assigned Numbers - 2025 - Bluetooth® Document
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf

Python for Security Professionals

  • 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
  • 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
  • 7. Let’s get started with the basics of Python
  • 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)
  • 18. Conditional statements: IF, ELSE, and ELIF p_list = [21,22,25,80] if p_list[0] == 21: print("FTP service") elif p_list == 22: print("SSH service") else: print("Unknown Service")
  • 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.
  • 25. Python script for brute forcing Gmail accounts