Python Hacking scripts | Hacking with python

Both professional penetration testers and hackers need to learn hacking with python. Years ago hackers used to use Linux-Shell scripts a lot. A couple of years later Perl and PHP were the popular scripting language for hacking. Now Python is the leading scripting language for hacking. Most of recent attacks can be constructed by Python and if you want to learn all the bits and bobs you can read this book “Violent Python: a Cookbook for Hackers”

In this article I intend to introduce libraries for hacking with python, most of which are taken from the aforementioned book and for a detailed discussion you can refer to that book.

Python language

Python is an interpreter-based language. This means to run python scripts you need python interpreter to be installed. Python support object oriented programming but it also can be used as a modular language. This means Python does not need neither Class structures nor a main method to be run. A Python script can begin by a line that does the purpose and just finishes. This tutorial is not going to be a python programming guide but just a complement for those already knows the python language. But again if you feel, you need some backgrounds you can read the aforementioned book. 

Python hacking script for socket Communication

Hackers often attack from a remote place using a network connection. There are numerous exploits and attacks that circumvent the typical communication scenario (between Client and Server) and communicate with the victim in an unusual way. For example, clients use internet browser applications to connect to a website and servers are supposed to serve with a typical Apache, IIS or etc. server. If everyone had followed this convention there were probably no security vulnerability reported for browsers. The vulnerability shows itself when you bypass all the standard behaviors and implement a custom TCP communication e.g. communicating from the server’s side by a small python script to leverage a vulnerability with the client Internet Explorer browser. This way you can exploit a buffer overflow vulnerability in client’s application such as Internet Explorer.

To implement a custom TCP connection you can use Python’s Socket library which is really easy to use. Writing a python hacking script for opening a connection, reading and sending data is as easy as:

from socket import *

connSkt = socket(AF_INET, SOCK_STREAM)

connSkt.connect(targetHost, targetPort)

connSkt.send('Data you want to send such as an exploit\r\n') #Sending data

results = connSkt.recv(100)  # Data to be read from the victim


Python hacking script for Port Scanning

Before any successful attack there should be a detailed footprinting phase. In an ordinary manual hacking scenario you do the footprining or enumeration phase using Nmap. But when you’re designing your own automated attack scenario and you want to perform an automatic hacking with python you cannot lean on a manual enumeration phase to combine with a python hacking script for exploit development. The best examples are worms; worms are pieces of codes that spread automatically. These Malware first scan their environment, find vulnerable hosts and then exploit them.

Good news is that you can use Nmap in your python hacking script. Install Nmap library for python from this address and then you can acquire Nmap in your codes like this:

nmScan = nmap.PortScanner()

nmScan.scan(targetHost, targetPort)

There are tons of options and results that you can read in your python script but for a simple result to see the status of scanned port you can use this line:



Interacting with other programs in python

There are times that you need the result of another program to perform your hacking with python. This result may be from ssh, a Torrent program (for a botnet scenario) or other commands. In Linux python scripts you can interact with other programs using Pexpect. Using Pexpect you can send your commands to other programs and check the results in order to take the next action. For example to interact with ssh, the following python snippet can be used:

import pexpect

comandString = 'ssh ' + user + '@' + host

child = pexpect.spawn(comandString)

result = child.expect([pexpect.TIMEOUT, 'Are you sure you want to continue connecting', '[P|p]assword:'])


In this example we first sent the command to OS ('ssh ’) and then defined the expected results:

  • Time out
  • Are you sure you want to continue connecting
  • [P|p]assword:

Depending on the results we defined, Pexpect returns a value and we can decide what to do next:

if result == 0: #TimeOut

   print '[-] Error Connecting'


if result == 1: # Are you sure you want to continue connecting


   result = child.expect([pexpect.TIMEOUT, '[P|p]assword:'])

if ret == 0:

   print '[-] Error Connecting' #TimeOut



child.expect(['# ', '>>> ', '> ', '\$ '])

return child.before


If the returned result is not “TimeOut” and is “Are you sure you want to continue connecting” we send “yes” and then expect '[P|p]assword:' to be returned. If everything is OK we then send the password for authentication and then expect these texts '# ', '>>> ', '> ', '\$ ' which show a successful authentication. child.before shows the last result from the ssh program.

While above python hacking script show the functionality of Pexpect, I recommend to interact with SSH, use pxssh library which has login(), logout() and prompt() methods.

Also pay attention that we use Pexpect when we need to interact with the program. If we want to just run a command we just use os.system. For example to run a Metasploit exploit in your python script, having that commands are stored in a file (meta.rc), we use:

import os

import sys

os.system('msfconsole -r meta.rc')



Automating FTP attacks

FTP servers are good candidates for attack, however finding a vulnerable FTP server manually is a very exhausting task. By a python hacking script you can automate FTP attacks. The Python library for FTP interaction is ftplib. This snippet shows the functionality:

import ftplib


   ftp = ftplib.FTP(hostname)

   ftp.login('Password', 'User')

   print '\n[*] ' + str(hostname) + ' FTP Anonymous Logon Succeeded.'

except Exception as e:

   print '\n[-] ' + str(hostname) + ' FTP Anonymous Logon Failed.'


dirList = ftp.nlst() # listing directories


f = open('FileName to write the result of a FTP Download', 'w')

ftp.retrlines('RETR ' +  'PageName to Download', f.write) # reading a FTP page to a file

ftp.storlines('STOR ' +  'PageName to Upload', open('FileName to upload')) # writing a File to a FTP page




Communicating with a web page in your python script | Parse a webpage | Stateful Programming

Either to attack a website automatically or parsing the data in a webpage you need Stateful Programming which in simple words is the process of communicating with a website by an identity that the website is aware of. For example a website may need a login before granting access to a webpage. A library like mechanize in Python provide a mechanism to login by the script and continue requesting protected webpages using the authenticated state. There are also other python libraries that help you to parse a webpage. Re, urllib, and urlparse are some of those. Following scripts show some functionality of these libraries:

import mechanize

import urllib

import re

import urlparse

browser = mechanize.Browser()'Url of the website you want to communicate with’) # Simple communication without GET or POST parameter

reqData = urllib.urlencode({'Post or GET parameter name': ‘Parameter value’, 'Post or GET parameter name': ‘Parameter value’}) # Preparing parameters to pass to the requested page'Url of the website you want to communicate with’, reqData) # Communication with GET or POST parameter

params = {}

params['ParameterName'] = ‘ParameterValue’

reqParams = urllib.urlencode(params) #Another way of preparing parameters

resp ='Url of the website you want to communicate with', reqParams).read() #Communicating the website and reading the response

ParsedValue = re.findall(r'regular expression', resp) # Parsing to find a value



To just read files or pages (regardless of the state) from a website you can use urllib2 library:

import urllib2

Contents = urllib2.urlopen(url).read()


A better library to parse html pages is Beautiful Soup. Finding all the image tags in a page is as easy as:

import urllib2

from bs4 import BeautifulSoup

urlContent = urllib2.urlopen(url).read()

soup = BeautifulSoup(urlContent)

imgTags = soup.findAll('img')

Other Useful methods for hacking with python

gethostbyname(targetHost) # Retrieve host name from dns name

gethostbyaddr(tgtIP) # Retrieve host name from IP address




Read 5711 times Last modified on Saturday, 18 July 2015 15:01
Rate this item
(0 votes)
About Author
Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

Advanced Programming Concepts
News Letter

Subscribe our Email News Letter to get Instant Update at anytime