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
Abhishek kumar
 
PPTX
Programming in Python
Tiji Thomas
 
PPTX
Tuples, Dicts and Exception Handling
PranavSB
 
PPTX
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Maulik Borsaniya
 
PPT
Intro to Functions Python
primeteacher32
 
PPTX
Intro to Python Programming Language
Dipankar Achinta
 
PPTX
Python Tutorial Part 1
Haitham El-Ghareeb
 
Python made easy
Abhishek kumar
 
Programming in Python
Tiji Thomas
 
Tuples, Dicts and Exception Handling
PranavSB
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Maulik Borsaniya
 
Intro to Functions Python
primeteacher32
 
Intro to Python Programming Language
Dipankar Achinta
 
Python Tutorial Part 1
Haitham El-Ghareeb
 

What's hot (20)

PPTX
Testing in Python: doctest and unittest (Updated)
Fariz Darari
 
PPTX
Testing in Python: doctest and unittest
Fariz Darari
 
PPTX
Python basics
Hoang Nguyen
 
PPTX
Fundamentals of Python Programming
Kamal Acharya
 
PPTX
Python 3 Programming Language
Tahani Al-Manie
 
PDF
4. python functions
in4400
 
PPTX
Functions, List and String methods
PranavSB
 
PDF
Introduction To Programming with Python
Sushant Mane
 
PPTX
Java I/O
Jayant Dalvi
 
PPTX
Basic Python Programming: Part 01 and Part 02
Fariz Darari
 
PPTX
Python ppt
Anush verma
 
PDF
Python basic
Saifuddin Kaijar
 
PPTX
Python 101: Python for Absolute Beginners (PyTexas 2014)
Paige Bailey
 
PDF
What is Python?
wesley chun
 
PDF
Python Basics
tusharpanda88
 
PPTX
Python for Beginners(v1)
Panimalar Engineering College
 
PDF
Introduction to Python for Bioinformatics
José Héctor Gálvez
 
PPTX
Python Seminar PPT
Shivam Gupta
 
PPTX
Introduction to Python Part-1
Devashish Kumar
 
PDF
Python Tutorial
AkramWaseem
 
Testing in Python: doctest and unittest (Updated)
Fariz Darari
 
Testing in Python: doctest and unittest
Fariz Darari
 
Python basics
Hoang Nguyen
 
Fundamentals of Python Programming
Kamal Acharya
 
Python 3 Programming Language
Tahani Al-Manie
 
4. python functions
in4400
 
Functions, List and String methods
PranavSB
 
Introduction To Programming with Python
Sushant Mane
 
Java I/O
Jayant Dalvi
 
Basic Python Programming: Part 01 and Part 02
Fariz Darari
 
Python ppt
Anush verma
 
Python basic
Saifuddin Kaijar
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Paige Bailey
 
What is Python?
wesley chun
 
Python Basics
tusharpanda88
 
Python for Beginners(v1)
Panimalar Engineering College
 
Introduction to Python for Bioinformatics
José Héctor Gálvez
 
Python Seminar PPT
Shivam Gupta
 
Introduction to Python Part-1
Devashish Kumar
 
Python Tutorial
AkramWaseem
 
Ad

Similar to Python for Security Professionals (20)

PDF
web programming UNIT VIII python by Bhavsingh Maloth
Bhavsingh Maloth
 
PDF
Tutorial on-python-programming
Chetan Giridhar
 
PPT
Introduction to python
Syed Zaid Irshad
 
PPTX
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
sangeeta borde
 
PPTX
Docketrun's Python Course for beginners.pptx
wafoxeg441
 
KEY
Programming with Python - Week 3
Ahmet Bulut
 
PPTX
FILE AND OBJECT<,ITS PROPERTIES IN PYTHON
ashima967262
 
PPT
Python ppt
Mohita Pandey
 
PDF
Python (3).pdf
samiwaris2
 
PPT
1B-Introduction_to_python.ppt
AmritMarwaha1
 
PPT
Python Programming Basic , introductions
M.H.Saboo Siddik Polytechnic
 
PPTX
INTRODUCTION TO PYTHON.pptx
Nimrahafzal1
 
PDF
W-334535VBE242 Using Python Libraries.pdf
manassingh1509
 
PPT
01-Python-Basics.ppt
VicVic56
 
PPT
ENGLISH PYTHON.ppt
GlobalTransLogistics
 
PDF
Python cheat-sheet
srinivasanr281952
 
PPTX
manish python.pptx
ssuser92d141
 
PPT
python1.ppt
VishwasKumar58
 
PPT
python1.ppt
RajPurohit33
 
PPT
Lenguaje Python
RalAnteloJurado
 
web programming UNIT VIII python by Bhavsingh Maloth
Bhavsingh Maloth
 
Tutorial on-python-programming
Chetan Giridhar
 
Introduction to python
Syed Zaid Irshad
 
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
sangeeta borde
 
Docketrun's Python Course for beginners.pptx
wafoxeg441
 
Programming with Python - Week 3
Ahmet Bulut
 
FILE AND OBJECT<,ITS PROPERTIES IN PYTHON
ashima967262
 
Python ppt
Mohita Pandey
 
Python (3).pdf
samiwaris2
 
1B-Introduction_to_python.ppt
AmritMarwaha1
 
Python Programming Basic , introductions
M.H.Saboo Siddik Polytechnic
 
INTRODUCTION TO PYTHON.pptx
Nimrahafzal1
 
W-334535VBE242 Using Python Libraries.pdf
manassingh1509
 
01-Python-Basics.ppt
VicVic56
 
ENGLISH PYTHON.ppt
GlobalTransLogistics
 
Python cheat-sheet
srinivasanr281952
 
manish python.pptx
ssuser92d141
 
python1.ppt
VishwasKumar58
 
python1.ppt
RajPurohit33
 
Lenguaje Python
RalAnteloJurado
 
Ad

Recently uploaded (20)

PDF
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPTX
The Future of AI & Machine Learning.pptx
pritsen4700
 
PDF
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PPTX
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
Software Development Methodologies in 2025
KodekX
 
PPTX
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
Doc9.....................................
SofiaCollazos
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
PDF
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
The Future of AI & Machine Learning.pptx
pritsen4700
 
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
Software Development Methodologies in 2025
KodekX
 
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
Doc9.....................................
SofiaCollazos
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 

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