Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Phython Library

Uploaded by

faizzte
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Phython Library

Uploaded by

faizzte
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Beginners Guide on Python for Cybersecurity

What is Python?

Python is high-level language, object-oriented interpreted programming language. It was


created by Guido van Rossum during 1985-1990. Python source code is available under
GNU General Public Licence (GPL).

Python is a must and very much useful for students and working professionals to
become a software engineer. Python is a language that can be used in most domains
nowadays. Python is object-oriented so doing encapsulation will be very much useful.
Python is interpreted language, hence compiling before fore ore executing is not
required and it can be executed directly. It can also be used as the scripting language. It
has an auto garbage collection feature.

• Python is easy to learn


• It has interactive mode
• It is portable means it can run on wide range of hardware devices
• Python supports GUI (Graphical User Interface) application to that can be transfer to many
windows systems
• For cybersecurity python can be used in various things like making tool, writing scripts, etc

Why Python for Cybersecurity?

1) Python is easy to learn and implement


Python is a lightweight language. It doesn’t require lengthy line of codes. It is
uncomplicated language. As you can see that python is straightforward so it will be
much easier to learn as compared to other programming languages like C, Java, etc.
Python requires minimal lines of codes

2) Python is open source

Python is an open-source programming language. Means anyone can give their


contribution like Linux is also an open source. Python has strong community because of
strong developers’ community which always try to make it better and better. Also,
python is free for use.
3) Automatic Memory Management

Python has built-in memory management system. This is very much helpful for
developers because they must be less concern about memory management. You do not
have to worry about caching, segmentation, etc.

4) Scripts in python can be created quickly

Biggest benefit for cybersecurity professional is that it makes scripting way much easier.
Many applications have limited backend coding. Sometime after an cyberattack or
during vulnerability assessment python has benefit because of its simplicity it takes
small amount of time to repair or to fix it

5) Python can be used for mostly everything in cybersecurity

If a cybersecurity professional is an expert in python and concept is crystal clear, then


they can do any task they want to. Like python can be used in making payloads, used
for malware analysis, decoding of packets, accessing servers, network scanning, port
scanning and many more. Python in cyber security can be used for automation too
which makes cybersecurity’s reconnaissance (information gathering) much more
effortless and time saving.

6) Python for cybersecurity is useful also because of its extensive libraries

Python has many libraries and frameworks which are very much useful and make work
of a cybersecurity professional easier. It is also very much useful for Pen Testing. But
for penetration testing you should first need to take and learn an ethical hacking
course These libraries make the script minimal and much more useful as compared to
other languages, Afterall python is the most straightforward language as compared to
languages like C, Java, etc.

Benefits of Python Programming

1) Productivity

Python can be considered as the most productive programming language. Because of


its simplicity developers can focus on main aim of project or on problem during any
assessment of vulnerability. It also optimizes memory allocation, because it requires
less line of codes so it will be easier for compiler to compile and run the Python program.
2) Interpreted Language

Python is also famous for its feature of being an interpreted language. Interpreted
means compiling is not required before executing the program. It directly executes the
code line by line.

3) Portability

It is portable across various operating system; hence unlike C/C++ we do not have to
write the code again for different platform.

So, it will be beneficial since we do not have to write the script/code again and again, it
will be time and effort efficient.

4) Vast library support

You can almost find any library in python standard library, because python’s standard
library is immense. Python’s standard library contains more than 200 crore library which
we can use for various purpose like making games, doing scientific or computational
analysis, GUI based desktop application, Database access, etc.

5) Child’s play to learn python programming

Python is a high-level programming language that has normal and easy English like
structure which is easy to learn, write and understand the code. You can write any
program in a smaller number of lines as compared to other programming language like
C/C++, Java, etc.

6) Dynamically Typed

Python is a dynamically typed language means you do not have to worry to always
declare the data type of the variable, it will automatically assign the type during the
execution according to its value. You can also go through KnowledgeHut cybersecurity
training. It is an amazing training to learn cybersecurity.

How Python is used by Cybersecurity Analysts?

Now the question must be that who are cybersecurity analysts? Cybersecurity Analyst
are the professional one who build and secure the IT organization’s network and
infrastructure.
Cybersecurity Analyst uses python for implementing the major check-ups by using the
automated script which can be created by using python. There are many libraries which
helps the professional to write efficient code in minimal line of code. It also contains
automated tools which can be customize according to their requirement. It can be used
to write automatic responses according to user’s input, but for that also one must
configure it according to their requirement. They can also make their own tools.

Cybersecurity analysts have to write their own automation code which obviously will be
beneficial to write in python because majority of time the domain will be vast and an
analysts can’t show any error code one by one on every server, for that a cybersecurity
analyst will write an automation code which will executed according to the configuration
.

How to Learn Python for Cybersecurity?

First, you need to learn python language by some training course or blog. Then you
have to practice python basics. Then specially for cybersecurity perspective you have to
start the scripting and learning the cryptographic algorithm for securing the files and
communication inside or outside the domain. There are also many books which will
teach you how python is used for penetration testing and many more field of
cybersecurity like bug hunting.

Conclusion

Python is and will be the most demanding programming and scripting language in the
coming future for cybersecurity, so keep digging for it and keep learning. The above
content will be very much helpful for beginner in python programming.

Always keep discovering new libraries and try to master them. If you do mastery in
python some job roles and path will be open for you in IT or cybersecurity field, but don’t
only rely on python because as I mentioned before only few job roles are there for only
python scripting. Keep hustling and learning the cybersecurity things, because learning
never end’s (specially in cybersecurity).
Frequently Asked Questions (FAQs)

1. What code do hacker use?

Hackers mostly uses scripting and for scripting they use python most of time.

2. What should I learn in python for cybersecurity?

Scripting and cryptographic Algorithm are great to learn in cybersecurity.

3. How python used in cybersecurity?

In cybersecurity python is used for automation, tools building, scripting and many more.

4. What are some python modules that are used for cybersecurity, and why?

Modules like pymetasploit3, scapy, cryptography, etc are used. Pymetasploit3 provides
Metasploit’s framework, scapy used to analyse packets, cryptography for securing the
communication.

5. Why is python preferred by most of the cybersecurity personnel?

Because python is easy to learn, and its scripting is very much powerful. It can also be
used on various operating systems because of its portability.

PYTHON FOR CYBER SECURITY – PURPOSE AND BENEFITS


Python is a general-purpose, server-side scripting language implemented by thousands of security projects. Some
of the functionalities supported using Python’s base programming do not require any third-party tools, examples
of which are given below:

• Attacks simulation
• Port Scanning
• Web Server Fingerprinting
• Access to mail servers
• Load generation and website testing
• Wireless network scanning
• Traffic transmission in the network
• Intrusion detection and prevention systems
The Top 14 Python Libraries for Cybersecurity

Python is most popular language because its free and straight forward means easy to
learn, requires less lines of code. Python’s library is vast. There are many libraires used
for cybersecurity like as follows:

1) Network security libraries

Tools like NMAP and Twisted are broadly used for scanning of network layer and
enumeration of ports, different application protocols.

Nmap is an open-source tool analyser that is widely used in cybersecurity. This


library enables you to integrate Nmap with your Python scripts, allowing you to
leverage Nmap’s capabilities to scan hosts and then interact with the results
within your Python script.

pip install python-nmap

How to Scan Nmap Ports


To scan Nmap ports on a remote system, enter the following in the terminal:

sudo nmap 192.168.0.1

Replace the IP address with the IP address of the system you’re testing. This is the basic format for Nmap, and
it will return information about the ports on that system.

In addition to scanning by IP address, you can also use the following commands to specify a target:

To scan a host:

nmap www.hostname.com

To scan a range of IP addresses (.1 – .10):


nmap 192.168.0.1-10

To run Nmap on a subnet:

nmap 192.168.0.1/13

To scan targets from a text file:

nmap –iL textlist.txt

Note: The developers at nmap.org provide a test server that you can experiment on, located at scanme.nmap.

Scan port 80 on the target system:

nmap –p 80 192.168.0.1

Scan ports 1 through 200 on the target system:

nmap –p 1-200 192.168.0.1

Scan (Fast) the most common ports:

nmap –F 192.168.0.1

To scan all ports (1 – 65535):

nmap –p– 192.168.0.1

To scan using TCP connect (it takes longer, but is more likely to connect):
nmap –sT 192.168.0.1

To perform the default SYN scan (it tests by performing only half of the TCP handshake):

nmap –sS 192.168.0.1

To instruct Nmap to scan UDP ports instead of TCP ports (the –p switch specifies ports 80, 130, and 255 in this
example):

nmap –sU –p 80,130,255 192.168.0.1

Run a fast scan on the target system, but bypass host discovery. (Host discovery uses ping, but many server
firewalls do not respond to ping requests. This option forces the test without waiting for a reply that may not be
coming):

nmap –Pn –F 192.168.0.1

The nmap utility can be used to detect the operating system of a particular target:

nmap –A 192.168.0.1

It can also be used to probe for the services that might be using different ports:

nmap –sV 192.168.0.1

2) Beautiful Soup

It is used for collecting the scrap data form webpage in form of HTML (Hyper Text
Markup Language) and XML (Extensible Markup Language).
The collection of data is a crucial part of penetration testing. Penetration testers
may need to extract data from HTML/XML sites on occasion. In big projects,
writing a tool from the start or even doing the procedure manually might take
hours or days.

Beautiful Soup is a Python module that may be used to automate data scraping
operations. For example, the library can read data from HTML and XML files and
parse them.

pip install beautifulsoup4

html_doc = """
<html>
<head>
<title>Test Page</title>
</head>
<body>
<p><b>This is a test page.</b></p>
</body>
</html>
"""

from bs4 import BeautifulSoupsoup = BeautifulSoup(html_doc, 'html.parser')for tag in


soup.find_all('b')
print(tag.name)# b

Python program to scrape website


#and save quotes from website
import requests
from bs4 import BeautifulSoup
import csv

URL = "http://www.values.com/inspirational-quotes"
r = requests.get(URL)

soup = BeautifulSoup(r.content, 'html5lib')

quotes=[] # a list to store quotes

table = soup.find('div', attrs = {'id':'all_quotes'})

for row in table.findAll('div',


attrs = {'class':'col-6 col-lg-3 text-center margin-30px-bottom
sm-margin-30px-top'}):
quote = {}
quote['theme'] = row.h5.text
quote['url'] = row.a['href']
quote['img'] = row.img['src']
quote['lines'] = row.img['alt'].split(" #")[0]
quote['author'] = row.img['alt'].split(" #")[1]
quotes.append(quote)

filename = 'inspirational_quotes.csv'
with open(filename, 'w', newline='') as f:
w = csv.DictWriter(f,['theme','url','img','lines','author'])
w.writeheader()
for quote in quotes:
w.writerow(quote)

3) YARA

It is used for malware identification and classification.

VirusTotal’s Yara is a tool for quickly identifying patterns in data. It’s like a
supercharged version of Ctrl+F. You can provide strings or regex patterns and
whether or not a condition or several criteria should be satisfied.

This module makes it simple to integrate Yara into your scripts. We can use it to
extract data from API requests that matched on yara criteria.

pip install yara-python

import yara

rule = yara.compile(source='rule foo: bar {strings: $a = "lmn" condition: $a}')


matches = rule.match(data='abcdefgjiklmnoprstuvwxyz')
print(matches)
>>[foo]

4) Mechanize

It is used for interacting with data. It is also used for SQL Injection and XSS (Cross Side
Scripting). It can used to catch data of webpage.

import mechanize

#This bot allows for autofill on the ShoezGallery Raffle.

browser = mechanize.Browser()
response = br.open("http://yeezy.shoezgallery.com/")

br.addheaders = [("User-agent","Mozilla/5.0")]

url = "http://yeezy.shoezgallery.com/"

browser.select_form(nr=0)

browser.form['nom'] = Last name

browser.form['prenom'] = First Name

browser.form['mail'] = my email here

browser.form['telephone'] = phone number here

browser.form['taille'] = 4313

browser.form['pays'] = Etats_Unis

brower.submit()

response = browser.open('http://yeezy.shoezgallery.com/')

print response.read()

5) Pymetasploit3

In this library you can use Metasploit framework to find different vulnerabilities on
different environment or platform like for mobile exploitation, Linux exploitation,
Windows exploitation.

Metasploit contain vast number of payloads.

6) Scapy

It is used for decoding packets, analysing packets, packet processing on any network.

pip install scapy


7) Cryptography Library

Cryptography libraries are used to secure or encrypt any file for process using
cryptographic algorithms.

This layer is known as the “hazardous materials” or “hazmat” layer because of the
risk potential when operating at this level. These are found in
the cryptography.hazmat package and their explanation will always include a
warning.

pip install cryptography

Fernet module is imported from the


# cryptography package
from cryptography.fernet import Fernet

# key is generated
key = Fernet.generate_key()

# value of key is assigned to a variable


f = Fernet(key)

# the plaintext is converted to ciphertext


token = f.encrypt(b"welcome to geeksforgeeks")

# display the ciphertext


print(token)

# decrypting the ciphertext


d = f.decrypt(token)

# display the plaintext


print(d)
8) Psscan

It is used to expose terminated process, means which process are already stopped.
This helps in finding the previous process from which we can find some information
about the attacker.

9) Pslist

It uses to show all process and verify which process how started and ended. This can
used to find the behaviour of the process.

Many more libraries are

10) Twisted

Twisted is network programming framework written in Python, which is developed by


Glyph Lefkowitz and it is licensed under MIT licence. Released on October 22, 2002. I
basically help us to create SMTP, SSH, HTTP servers, etc with more accuracy and
ease.

11) Pylibnet

Pylibnet is a python module used for injection of libnet packets. Basically, libnet is an
API which is used for creation and injection of network packets. It is also used for
construction of network packets at IP layer, Link layer and as the host of supplementary
and complementary functionality

12) RawSocketPy

Raw Socket is a layer 2 python library which is used for communication using only MAC
address. This allows us to make custom Wi-Fi/Ethernet communication system which is
made without using IP, TCP or UDP.

13) Pwntools

Pwntools is a CTF toolkit which is a CTF framework and exploit development library. It
is used for fast development of exploit writing with peak ease.
14) Requests

Request in python will allow you to send HTTP/1.1 requests. It will give us all content,
encoding, status as a response object. Response object contains the server’s response
to the HTTP request. There are many more useful libraries too, above listed are the
famous one.

pip install requests

15) Boto3

Boto3 is the Amazon Web Services (AWS) Software Development Kit (SDK) for Python,
which allows programmers to write scripts that can interact with AWS services like
Amazon Simple Storage Service(S3), Amazon Elastic Compute Cloud(EC2), and
Amazon Virtual Private Cloud(VPC).

With Boto3 you can start and stop servers on demand, cancel instances that do not
conform to your organization’s security standards, perform updates and patch
management, and much more. Being familiar with this SDK is very valuable for any
professional working with AWS.
Boto3: using waiter to poll a new EC2 instance for a running state— image by the author

16) Regex

Regex stands for regular expressions, and this is a tool that allows you to search for
specific patterns within a block of text. This is a very useful function for extracting
information from log files during an investigation or when scraping information from the
internet.

By combining this library with other standard Python libraries, you can create some very
useful programs. For example, you can use regex to search log files and locate IP
addresses so you can determine if someone was able to hack into your network, what
actions they performed, and what time this event took place.
Print a list of all matches:

import re

txt = "The rain in Spain"


x = re.findall("ai", txt)
print(x)
import re

txt = "The rain in Spain"


x = re.search(r"\bS\w+", txt)
print(x.string)

17) Pyautogui and Web Browser

Pyautogui allows your scripts to control mouse and keyboard functions, letting you
imitate intelligent user behavior. The web browser module allows you to launch a new
browser to a specified URL.

For example I’ve seen a Python script that automates the process of testing web pages
for XSS scripting vulnerabilities. XSS is a cyberattack that tries to insert javascript code
into an input form and have that code run on the website.

These libraries can also be used to automate other routine tasks that require you to
login, go to a web browser, and perform an action on the webpage.

1. import pyautogui
2. screenWidth, screenHeight = pyautogui.size() # returns the monitor size
3. print("The Screen Width is: ", screenWidth)
4. print("The Screen Height is: ", screenHeight)

The Screen Width is: 1366

The Screen Height is: 768

Example -

1. print(pyautogui.onScreen(500, 600))
2. print(pyautogui.onScreen(0, 1500))

Output:

True
False

We have provided the 0 to 1500 which is beyond the screen's dimension that's why it returned the
False.
Basic Mouse Functions
This section will cover how to automate the mouse using the pyautogui library. Below are some
commonly used mouse manipulation methods like moving the cursor from one point to another and
automatically clicking buttons. Let's see the following methods.

The moveTo() Method -


It moves the mouse to the XY coordinate. It takes the three parameters - X, Y coordinates, and duration
(set the duration in the given duration).

1. pyautogui.moveTo(100, 150, duration = 10)

The cursor moves to the mentioned coordinates according to the given time duration when running
the above function. The duration is time in seconds. We passed the ten seconds means the cursor will
take ten seconds to locate the coordinates.creen Width is: 1366

The Screen Height is: 7


18) Pyperclip

It’s particularly useful for any scripts that involve large bodies of text. For example, say
you’re scanning an entire pdf for names, addresses, and phone numbers. Just by
highlighting the pdf text and copying it to clipboard, pyperclip allows you to use it in your
script as an input, saving you a significant amount of time.
Output :
100

Note : Copy function will convert every data type to string

19) Faker

This library is dedicated to producing fake data that can be used to test your programs.
This is important to ensure that whatever scripts or tools you write will be able to
perform the action as intended.

For example, if you have a script that extracts URLs, you may want to generate some
fake text containing that information and test your program to ensure that your script
can find it effectively. Faker can generate random data such as names, addresses,
emails, countries, text, urls, etc.

Just call faker.name() and you’ll get a random name, faker.address() and you'll get a fake address.
20) Python Nmap

Nmap is a very widely used port scanner. Port scanning is the process of checking what
ports are open on a computer and what services are running on that machine so you
can start to determine how that machine may be vulnerable to getting hacked.

The Python Nmap library makes it easy for you to utilize nmap functionality through your
Python scripts, speeding up the process of scanning a target computer for
vulnerabilities and giving you more customization in your scans. This library allows you
to analyse nmap scan results, perform custom scans, and import nmap results into
other tools.

21) Socket

Socket is a low-level network interfacing library that allows you to establish client-server
connections. In the context of cybersecurity, this is important because it allows you to
connect to any machine on a specified port, with a specific protocol, and send data to
that machine.This can be used for port scanning of a machine as well as sending data
to or extracting information from a machine. Data exfiltration occurs at a later stage of
pen testing and is known as exploitation. Any project that requires you to communicate
over a network interface will likely use Socket.
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
You can also find the IP using python:
import socket

ip = socket.gethostbyname('www.google.com')
print ip

You might also like