Python For Penetration Testers

Wow!

vulnerablelife


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.



Network

  • 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.

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(proc.pid, 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/")


List

1.Join list items with delimiter

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

Time

1.Print data and time. Find more at strftime.org

  • %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")
'17:47:17'
>>> 
>>> time.strftime("%d/%m/%Y %H:%M:%S")
'14/03/2017 17:47:26'
>>>

2. Epoch time: int(time.time()) https://www.epochconverter.com/


Reading and writing from/to different file formats

1.YAML Files

Reading

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

Writing

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

Miscellaneous:

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

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

--OUTPUT--
Inside of function f1
Caller Name: f1

 

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

Arguments:

  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')
levels={"info":logging.INFO,
        "debug":logging.DEBUG,
        "warning":logging.WARNING,
        "error":logging.ERROR,
        "critical":logging.CRITICAL}

def log_it(level,message):
    log.setLevel(levels[level])
    log.addHandler(handler)
    handler.setLevel(levels[level])
    if level=="info":    
        log.info(message)    
    elif level=="debug":
        log.debug(message)
    elif level=="warning":
        log.warning(message)
    elif level=="error":
        log.error(message)
    elif level=="critical":
        log.critical(message)

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

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