in ,

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.

Task

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. server_script.py -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.

References

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 = '127.0.0.1', 777
 
def handler(signum, frame):
  print 'Starting...'
  raise IOError("Timmer tripped, shutting down...")
 
time_seconds = 0
 
# Catch command line argument -s
try:
  opts, args = getopt.getopt(sys.argv[1:],"hs:")
except getopt.GetoptError:
  sys.exit(2)
for opt, arg in opts:
if opt in ("-s"):
time_seconds = arg
 
signal.signal(signal.SIGALRM,handler)
signal.alarm(int(time_seconds))
 
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.bind((HOST, PORT))
# Listen for connections
listen_socket.listen(1)
print 'Serving on port %s ' % PORT
while True:
  client_connection, client_address = listen_socket.accept()
  request = client_connection.recv(1024)
  print request
 
signal.alarm(0)

Screen Shot 2016-07-27 at 6.02.21 PM

References   [ + ]

1. HOST, PORT

What do you think?

0 points
Upvote Downvote

Total votes: 0

Upvotes: 0

Upvotes percentage: 0.000000%

Downvotes: 0

Downvotes percentage: 0.000000%

Written by Admin

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.

Comments

Leave a Reply

Loading…

Ruby Performance Testing with Watir

Python – Processes