mardi 4 août 2015

News serveur (echo) et client en python

Bonjour ,

Je viens partager avec vous un nouvel exercice auquel j'ai du répondre. En fait j'ai tenté de réunir 3 exercices en 1.


Voici les 3 énoncés:
Citation:

-create tcp server which listen to a port
-implement signal to insure it automatically shut down
after a pre_configured duration , which is given via command-line
EG: tcp-server -t 100
shutdown after listening for port for 100 seconds

-Create a simple echo server to handle 1 client

-create a multi-threaded echo server

Voici le Script du serveur:

Code:

#-------------------------------------------------------------------------------
# -create tcp server which listen to a port
# -implement signal to insure it automatically shut down
#  after a pre_configured duration , which is given via command-line
#        EG: tcp-server -t 100
#        shutdown after listening for port for 100 seconds
#-------------------------------------------------------------------------------
# -Create a simple echo server to handle 1 client
#-------------------------------------------------------------------------------
# -create a multi-threaded echo server
#-------------------------------------------------------------------------------



#!/usr/bin/env python

import argparse
import socket
import threading
import signal
import sys

host = "127.0.0.1"
port = 5501
addr = (host, port)

parser = argparse.ArgumentParser(description = "TCP shutdown after X seconds")   
parser.add_argument("-t", dest="time", action="store", help="The timeout before the server close", type=int)
args = parser.parse_args()

def SigHandler(signum , frm):
    print "Timeout of {} seconds reached".format(args.time)
    print "Signal handler with signal {}".format(signum)
    print"No connection recieved"
    sys.exit(0)



class EchoThread(threading.Thread):
        def __init__(self, client, ip):
                threading.Thread.__init__(self)
                self.client=client
                self.ip=ip

        def run(self):
                i=threading.currentThread()
                print "The executing thread is:{}".format(i)
                print"Starting ECHO output"
                data="test"
                print "Recieved connection from:{} ".format(self.ip)
                while len(data):                   
                    signal.alarm(0)
                    data = self.client.recv(1024)
                    print"Client send :{}".format(data)
                    self.client.send(data)   
                print "Closing connection..."
                signal.alarm(args.time)
                self.client.close()

signal.signal(signal.SIGALRM , SigHandler)
tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpSocket.bind((addr))
tcpSocket.listen(4)
print"Waiting for a client..."
signal.alarm(args.time)

while True:
    (client, (ip, port))=tcpSocket.accept()
    thread = EchoThread(client, ip)
    thread.start()
    print"New client connected"

Voici le script du client:
Code:

import socket

def main():
    host = "127.0.0.1"
    port = 5501
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.connect((host,port))
    message = raw_input("->")
    while message != "q":
        s.send(message.encode("UTF-8"))
        data = s.recv(1024).decode("UTF-8")
        print "Received from server: {}".format(data)
        message = raw_input("->") 
    s.close()

if __name__ == "__main__":
    main()

Le serveur doit être démarré par le terminal. Si vous ne démarrez aucun client le serveur se fermera après le compteur que vous aurez entré avec -t, comme expliqué dans l'énoncé. Si vous démarrez un client il vous faudra taper q pour quitter

Résultat sans client:
Terminal
Citation:

terminal:~/Bureau$ python2 tcp_server_echo_argparse_threadin_v0.py -t 20
Waiting for a client...
Timeout of 20 seconds reached
Signal handler with signal 14
No connection recieved
terminal:~/Bureau$
Résultat avec client:
Terminal
Citation:

terminal:~/Bureau$ python2 tcp_server_echo_argparse_threadin_v0.py -t 20
Waiting for a client...
The executing thread is: <EchoThread(Thread-1, started -1226486976)>
Starting ECHO output
Recieved connection from: 127.0.0.1
New client connected
Client send Bonjour
Client send
Closing connection...
Timeout of 20 seconds reached
Signal handler with signal 14
No connection recieved
terminal:~/Bureau$
Python shell
Citation:

>>>
->Bonjour
Received from server: Bonjour
->q
>>>

Une copie de l'aide pour le serveur:

Citation:

terminal:~/Bureau$ python2 tcp_server_echo_argparse_threadin_v0.py -h
usage: tcp_server_echo_argparse_threadin_v0.py [-h] [-t TIME]

TCP shutdown after X seconds

optional arguments:
-h, --help show this help message and exit
-t TIME The timeout before the server close

Que pensez vous du script que je propose en solution ?


from Hackademics : Forum de hacking – hackers white hat – cours de securite informatique, apprendre langage python, tutoriels de reverse engineering http://ift.tt/1N8qS7S
via IFTTT

Aucun commentaire:

Enregistrer un commentaire