Python & Pentesting: Signals Exercise

At the Pentester Academy I took a course called Pentesting with Python.  It’s a great course… if you have an interest in Python and Security, I highly recommend it.


The instructor (Vivek Ramachandran) provides student exercises at the end of most of the lectures.  In lesson 16 (on signaling) he asks the students to write a Python script that does the following:

  1. Create a TCP server that binds to a socket
  2. Create signals to ensure it automatically shuts down after a pre-configured duration which is given from the command line as an argument (i.e. -s 10
  3. Shutdown the server after listening on the port for X seconds

My solution required a bit of research… I wasn’t sure how to create a server in Python (rusty on this) and also needed to research python signals on alarms.  I also wasn’t sure how to pass in command line arguments to the application.


For reference I used the following resources:

Raw Attempt

My raw attempt here isn’t very OO… it simply gets the job done.  I’d like to revisit it in the future and make it more OO.

import socket
import signal
import sys, getopt
# Defining host and port to server on
HOST, PORT = '', 777
def handler(signum, frame):
  print 'Starting...'
  raise IOError("Timmer tripped, shutting down...")
time_seconds = 0
# Catch command line argument -s
  opts, args = getopt.getopt(sys.argv[1:],"hs:")
except getopt.GetoptError:
for opt, arg in opts:
if opt in ("-s"):
time_seconds = arg
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.bind((HOST, PORT))
# Listen for connections
print 'Serving on port %s ' % PORT
while True:
  client_connection, client_address = listen_socket.accept()
  request = client_connection.recv(1024)
  print request

Screen Shot 2016-07-27 at 6.02.21 PM

Leave your vote

0 points
Upvote Downvote

Total votes: 0

Upvotes: 0

Upvotes percentage: 0.000000%

Downvotes: 0

Downvotes percentage: 0.000000%

References   [ + ]

About Admin 329 Articles
I work for a Telecom company writing and testing software. My passion for writing code is expressed through this blog. It's my hope that it gives hope to any and all who are self-taught.