SlideShare a Scribd company logo
1 of 26
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
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
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 script for brute forcing Gmail accounts
Thank You.

More Related Content

What's hot

Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)Fariz Darari
 
Testing in Python: doctest and unittest
Testing in Python: doctest and unittestTesting in Python: doctest and unittest
Testing in Python: doctest and unittestFariz Darari
 
Fundamentals of Python Programming
Fundamentals of Python ProgrammingFundamentals of Python Programming
Fundamentals of Python ProgrammingKamal Acharya
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming LanguageTahani Al-Manie
 
4. python functions
4. python   functions4. python   functions
4. python functionsin4400
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methodsPranavSB
 
Introduction To Programming with Python
Introduction To Programming with PythonIntroduction To Programming with Python
Introduction To Programming with PythonSushant Mane
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Fariz Darari
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Paige Bailey
 
Introduction to Python for Bioinformatics
Introduction to Python for BioinformaticsIntroduction to Python for Bioinformatics
Introduction to Python for BioinformaticsJosé Héctor Gálvez
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPTShivam Gupta
 
Introduction to Python Part-1
Introduction to Python Part-1Introduction to Python Part-1
Introduction to Python Part-1Devashish Kumar
 

What's hot (20)

Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)
 
Testing in Python: doctest and unittest
Testing in Python: doctest and unittestTesting in Python: doctest and unittest
Testing in Python: doctest and unittest
 
Python basics
Python basicsPython basics
Python basics
 
Fundamentals of Python Programming
Fundamentals of Python ProgrammingFundamentals of Python Programming
Fundamentals of Python Programming
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
 
4. python functions
4. python   functions4. python   functions
4. python functions
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
 
Introduction To Programming with Python
Introduction To Programming with PythonIntroduction To Programming with Python
Introduction To Programming with Python
 
Java I/O
Java I/OJava I/O
Java I/O
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02
 
Python ppt
Python pptPython ppt
Python ppt
 
Python basic
Python basicPython basic
Python basic
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)
 
What is Python?
What is Python?What is Python?
What is Python?
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Python for Beginners(v1)
Python for Beginners(v1)Python for Beginners(v1)
Python for Beginners(v1)
 
Introduction to Python for Bioinformatics
Introduction to Python for BioinformaticsIntroduction to Python for Bioinformatics
Introduction to Python for Bioinformatics
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
 
Introduction to Python Part-1
Introduction to Python Part-1Introduction to Python Part-1
Introduction to Python Part-1
 
Python Tutorial
Python TutorialPython Tutorial
Python Tutorial
 

Similar to Python for Security Professionals

web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh MalothBhavsingh Maloth
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programmingChetan Giridhar
 
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptxsangeeta borde
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3Ahmet Bulut
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdfsamiwaris2
 
1B-Introduction_to_python.ppt
1B-Introduction_to_python.ppt1B-Introduction_to_python.ppt
1B-Introduction_to_python.pptAmritMarwaha1
 
INTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptxINTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptxNimrahafzal1
 
01-Python-Basics.ppt
01-Python-Basics.ppt01-Python-Basics.ppt
01-Python-Basics.pptVicVic56
 
manish python.pptx
manish python.pptxmanish python.pptx
manish python.pptxssuser92d141
 
pysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
pysdasdasdsadsadsadsadsadsadasdasdthon1.pptpysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
pysdasdasdsadsadsadsadsadsadasdasdthon1.pptkashifmajeedjanjua
 

Similar to Python for Security Professionals (20)

web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
 
Python ppt
Python pptPython ppt
Python ppt
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
 
1B-Introduction_to_python.ppt
1B-Introduction_to_python.ppt1B-Introduction_to_python.ppt
1B-Introduction_to_python.ppt
 
INTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptxINTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptx
 
01-Python-Basics.ppt
01-Python-Basics.ppt01-Python-Basics.ppt
01-Python-Basics.ppt
 
ENGLISH PYTHON.ppt
ENGLISH PYTHON.pptENGLISH PYTHON.ppt
ENGLISH PYTHON.ppt
 
Python cheat-sheet
Python cheat-sheetPython cheat-sheet
Python cheat-sheet
 
manish python.pptx
manish python.pptxmanish python.pptx
manish python.pptx
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Python Basics
Python BasicsPython Basics
Python Basics
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Lenguaje Python
Lenguaje PythonLenguaje Python
Lenguaje Python
 
pysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
pysdasdasdsadsadsadsadsadsadasdasdthon1.pptpysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
pysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
 
coolstuff.ppt
coolstuff.pptcoolstuff.ppt
coolstuff.ppt
 

Recently uploaded

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 

Recently uploaded (20)

Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 

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
  • 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
  • 6.
  • 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.
  • 24.
  • 25. Python script for brute forcing Gmail accounts