Book Image

Python for Security and Networking - Third Edition

By : José Ortega
4 (2)
Book Image

Python for Security and Networking - Third Edition

4 (2)
By: José Ortega

Overview of this book

Python’s latest updates add numerous libraries that can be used to perform critical security-related missions, including detecting vulnerabilities in web applications, taking care of attacks, and helping to build secure and robust networks that are resilient to them. This fully updated third edition will show you how to make the most of them and improve your security posture. The first part of this book will walk you through Python scripts and libraries that you’ll use throughout the book. Next, you’ll dive deep into the core networking tasks where you will learn how to check a network’s vulnerability using Python security scripting and understand how to check for vulnerabilities in your network – including tasks related to packet sniffing. You’ll also learn how to achieve endpoint protection by leveraging Python packages along with writing forensics scripts. The next part of the book will show you a variety of modern techniques, libraries, and frameworks from the Python ecosystem that will help you extract data from servers and analyze the security in web applications. You’ll take your first steps in extracting data from a domain using OSINT tools and using Python tools to perform forensics tasks. By the end of this book, you will be able to make the most of Python to test the security of your network and applications.
Table of Contents (23 chapters)
1
Section 1: Python Environment and System Programming Tools
4
Section 2: Network Scripting and Packet Sniffing with Python
8
Section 3: Server Scripting and Port Scanning with Python
12
Section 4: Server Vulnerabilities and Security in Web Applications
16
Section 5: Python Forensics
20
Assessments – Answers to the End-of-Chapter Questions
21
Other Books You May Enjoy
22
Index

Port scanning and traceroute with scapy

In the same way we do port-scanning with tools like nmap, we can also execute a simple port scanner that tells us if a specific host and ports, are open, closed or filtered with scapy.

Port scanning with scapy

In the following example, we define the analyze_port() method, which provides the host, port, and verbose_level parameters. This method is responsible for sending a TCP packet and waiting for its response. When processing the response, the objective is to check within the TCP layer if the received flag corresponds to a port in an open, closed, or filtered state. You can find the following code in the scapy_port_scan.py file inside the scapy's port_scanning folder:

import sys 
from scapy.all import *
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
def analyze_port(host, port, verbose_level):
    print("[+] Scanning port %s" % port)
    packet = IP(dst=host)/TCP(dport=port,flags...