Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

Python & Pentesting: Signals Exercise

$
0
0

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:

Create a TCP server that binds to a socket Createsignals 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 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:

http://www.pentesteracademy.com/course?id=1 (the course itself) https://ruslanspivak.com/lsbaws-part1/ (creating a python server binding to a port) https://docs.python.org/2/library/signal.html (doc on signaling in python) https://docs.python.org/2/library/getopt.html (helped with command line arguments) 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)
Python & Pentesting: Signals Exercise

Viewing all articles
Browse latest Browse all 9596

Trending Articles