Python For Penetration Testers



Python for penetration testers

If you are involved in vulnerability research, reverse engineering or penetration testing, I suggest to try out the Python programming language. It has a rich set of useful libraries and programs. This page lists some of them.

Most of the listed tools are written in Python, others are just bindings for existing C libraries, i.e. they make those libraries easily usable from Python programs.


  • Scapy: send, sniff and dissect and forge network packets. Usable interactively or as a library
  • pypcapPcapy and pylibpcap: several different bindings for libpcap
  • libdnet: low-level networking routines, including interface lookup and Ethernet frame transmission
  • dpkt: fast, simple packet creation/parsing, with definitions for the basic TCP/IP protocols
  • Impacket: craft and decode network packets. Includes support for higher-level protocols such as NMB and SMB
  • pynids: libnids wrapper offering sniffing, IP defragmentation, TCP stream reassembly…

View original post 1,027 more words


Python tips and tricks

**Below snippets, tips, trick and concepts actively collecting from various web sites and stack-overflow questions.

**You can find some examples snippets and useful tools at my repo

Operations on String

1.Check the string s is alphanumeric or not s.isalnum()

os & sys Module

1.Kill process from python (The script should run with sudo)

def kill(proc, signum=signal.SIGTERM):
    os.killpg(, signum)

2.Get pid of current script that is running:  os.getpid()

3.Give nice to the script that is running: os.nice(19)

4.Get the current python version: sys.version_info

5.Rename files: os.rename(src, dst)

6.Check file exists or not: os.path.exists("/path/to/file")

7.Get directory name of file: os.path.dirname(/path/to/file.txt)

8.Create directories recursively: os.makedirs("/dir1/dir2/")


1.Join list items with delimiter

>> days=["Sunday","Monday","Tuesday", "Wednesday","Thursday","Friday", "Saturday"]
>>> "-".join(days)


1.Print data and time. Find more at

  • %H– 24 Hours hour
  • %I– 12 Hours hour
  • %M– Minutes
  • %S-Seconds
  • %d– Days
  • %m– Months
  • %Y– Year [4 Digits]
  • %j– Day of the year
  • %A– Day of the week (Name)
>>> import time
>>> time.strftime("%H:%M:%S")
>>> time.strftime("%d/%m/%Y %H:%M:%S")
'14/03/2017 17:47:26'

2. Epoch time: int(time.time())

Reading and writing from/to different file formats

1.YAML Files


def read_yaml(file_name):
    if not os.path.exists(file_name):
        print "{} not found! Please check.".format(file_name)
    with open(file_name) as f:
    return data


def write_yaml(data,yaml_file):
    with, 'w', encoding='utf8') as outfile:
        yaml.dump(data, outfile, default_flow_style=False, allow_unicode=True)


1. Know who is calling the function with inspect module (In-Built)

import inspect
def f1(): 
    print "Inside of function f1"    
def f2():
    curframe = inspect.currentframe()
    calframe = inspect.getouterframes(curframe, 2)
    print 'Caller Name:', calframe[1][3]

Inside of function f1
Caller Name: f1


2.Log rotate. (Include the below function in your script).


  1. message– Your information
  2. level– Log Level: debug, info, warning, error, critical
import logging
from logging.handlers import RotatingFileHandler

DEFAULT_LOG = '/var/log/script.log'
handler=RotatingFileHandler(DEFAULT_LOG, mode='a', maxBytes=20*1024*1024, backupCount=0, encoding=None, delay=0)
handler.setFormatter(logging.Formatter('%(asctime)s %(name)s[%(process)d] %(levelname)s: %(message)s'))
log =logging.getLogger('MyScript')

def log_it(level,message):
    if level=="info":       
    elif level=="debug":
    elif level=="warning":
    elif level=="error":
    elif level=="critical":

log_it("warning","Something happened!")

2017-03-14 12:19:53,391 MyScript[7602] WARNING: Something happened!;

3. Suppress all warnings in Python

import warnings