I am trying to build a HTTP server in python,
that sniffs packets and sends them to an other interface.
the server can get routing paths through a POST http request.
So that I need that the server will parallely sniff pakets and listen to http requests.
this is my code:
from scapy.all import *
from scapy.layers.inet import IP, UDP
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
from socketserver import ThreadingMixIn
import threading
ROUTING_LIST = []
INTERFACE_TO_SNIFF = 'vEthernet'
PORT = 80
class Route:
def __init__(self):
self.first_IP_src = ""
self.first_port_src = ""
self.first_IP_dst = ""
self.first_port_dst = ""
self.first_iface = ""
self.second_IP_src = ""
self.second_port_src = ""
self.second_IP_dst = ""
self.second_port_dst = ""
self.second_iface = ""
class Server(BaseHTTPRequestHandler):
# POST echoes the message adding a JSON field
def do_POST(self):
# read the message and convert it into a python dictionary
length = int(self.headers['Content-length'])
message = self.rfile.read(length)
routing_dict = json.loads(message, strict=False)
if add_routing_http(routing_dict) is True:
print("New Routing received:")
print("{" + "\n".join("{!r}: {!r},".format(k, v) for k, v in routing_dict.items()) + "}")
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(
("POST routing request received! now we have " + str(len(ROUTING_LIST)) + " routes").encode("utf8"))
def run_server():
global PORT
server_address = ('', PORT)
httpd = HTTPServer(server_address, Server)
print('Starting httpd on port %d...' % PORT)
httpd.serve_forever()
def add_routing_local(first_IP_src, first_port_src, first_IP_dst, first_port_dst, first_iface,
second_IP_src, second_port_src, second_IP_dst, second_port_dst, second_iface):
global ROUTING_LIST
temp = Route()
temp.first_IP_src = first_IP_src
temp.first_port_src = first_port_src
temp.first_IP_dst = first_IP_dst
temp.first_port_dst = first_port_dst
temp.first_iface = first_iface
temp.second_IP_src = second_IP_src
temp.second_port_src = second_port_src
temp.second_IP_dst = second_IP_dst
temp.second_port_dst = second_port_dst
temp.second_iface = second_iface
ROUTING_LIST.append(temp)
def add_routing_http(routing_dict):
global ROUTING_LIST
temp = Route()
temp.first_IP_src = routing_dict.get('firstIpSrc')
temp.first_port_src = routing_dict.get('firstPortSrc')
temp.first_IP_dst = routing_dict.get('firstIpDst')
temp.first_port_dst = routing_dict.get('firstPortDst')
temp.first_iface = routing_dict.get('firstIface')
temp.second_IP_src = routing_dict.get('secondIpSrc')
temp.second_port_src = routing_dict.get('secondPortSrc')
temp.second_IP_dst = routing_dict.get('secondIpDst')
temp.second_port_dst = routing_dict.get('secondPortDst')
temp.second_iface = routing_dict.get('secondIface')
ROUTING_LIST.append(temp)
return True
def packets_filter(packet):
return IP in packet and UDP in packet and Raw in packet
def match_packet(packet, routing):
match = True
if routing.first_IP_src != '' and packet[IP].src != routing.first_IP_src:
return False
if routing.first_IP_dst != '' and packet[IP].dst != routing.first_IP_dst:
return False
if routing.first_port_src != '' and packet[UDP].sport != routing.first_port_src:
return False
if routing.first_port_dst != '' and packet[UDP].dport != routing.first_port_dst:
return False
if routing.first_iface != '' and packet.sniffed_on is not None and routing.first_iface != packet.sniffed_on:
return False
return True
def handle_packet(packet):
global ROUTING_LIST
for routing in ROUTING_LIST:
if match_packet(packet, routing) is True:
new_packet = packet.copy()
new_packet[IP].src = routing.second_IP_src
new_packet[IP].dst = routing.second_IP_dst
new_packet[UDP].sport = routing.second_port_src
new_packet[UDP].dport = routing.second_port_dst
new_packet.show()
sendp(new_packet) # sendp(new_packet, iface=routing.second_iface)iface='eth0'
return
def main():
daemon = threading.Thread(name='daemon_server', target=run_server, args=())
daemon.setDaemon(True) # Set as a daemon so it will be killed once the main thread is dead.
daemon.start()
print("start sniffing")
sniff(lfilter=packets_filter, prn=handle_packet) # sniff(lfilter=packets_filter, prn=handle_packet, iface=INTERFACE_TO_SNIFF)
if __name__ == "__main__":
main()
In short - I wantthe main function to run in parallel both of functions: run_server, sniff. if I try to run inly one of them - both work great.
In this code only the run_server works but not the sniffing.
What is wrong?
thank you
You have created Thread only for the run_server method. In order to run the sniff function on multithreaded, you will have to create a thread for the sniff function too.
You can learn about basic multithreading from this document:
https://www.geeksforgeeks.org/multithreading-python-set-1/
Related
I wanted to demonstrate Asynchronous Non-Blocking threads through an EventLoop using a chatroom that I coded out in Python.
The chatroom is working fine when I simulate a server and clients on my desktop, but whenever I want to send packets over the internet to my friends who stay at a geographically distant location, I receive Timeout errors.
Obviously, I change the IP_ADDR accordingly while doing so. In fact, I have tried both IPv4 and IPv6. The firewall is off, and there are no anti-viruses installed.
I tried setting the timeout options as well, but the problem still exists.
Over a small geographical distance, the connection works.
I have also checked whether I am even able to send packets over the Internet at all to the target computer using the tracert command, and it seems like I can.
Server.py
import sys
import select
import msvcrt
import socket
IP_ADDR = socket.gethostbyname(socket.gethostname())
PORT = 5555
HEADER_SIZE = 10
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((IP_ADDR, PORT))
def add_header(username, msg):
username = f'{len(username) :< {HEADER_SIZE}}' + username
msg_len = len(msg)
msg = username + f'{msg_len :< {HEADER_SIZE}}' + msg
return msg.encode("utf-8")
sock_list = [server]
sock_dict = {server : 'Server'}
def broadcast_message(client, broadcast_msg):
try: #EAFP
client.send(broadcast_msg)
except:
username = sock_dict[client]
del sock_dict[client]
sock_list.remove(client)
broadcast_msg = add_header(sock_dict[server], f"{username} has left the group!!")
for clients in sock_list:
if clients is server:
print(f"{username} has left the group!!")
else:
broadcast_message(clients, broadcast_msg)
server.listen()
while True:
readers, _, err_sockets = select.select(sock_list, [], [], 1)
if(msvcrt.kbhit()):
msg = input("[:] >> ")
#msg = sys.stdin.readline()[:-1]
msg = add_header(sock_dict[server], msg)
for client in sock_list:
if client is server:
continue
else:
broadcast_message(client, msg)
for reader in readers:
if reader is server:
client_socc, client_addr = server.accept()
try:
client_username = client_socc.recv(1024).decode("utf-8")
if not len(client_username):
continue
else:
print(f"Connection accepted from {client_username[HEADER_SIZE : ].title()} : {client_addr[0]} : {client_addr[1]}")
sock_dict[client_socc] = client_username[HEADER_SIZE : ].title()
sock_list.append(client_socc)
broadcast_msg = add_header(sock_dict[server], f"{sock_dict[client_socc]} has joined the group!!")
for client in sock_list:
if client is server or client is client_socc:
continue
else:
broadcast_message(client, broadcast_msg)
except:
continue
else:
try:
client_msg = reader.recv(1024).decode("utf-8")
if not len(client_msg):
del sock_dict[reader]
sock_list.remove(reader)
else:
while len(client_msg):
broadcast_msg = add_header(sock_dict[reader], client_msg[HEADER_SIZE : HEADER_SIZE + int(client_msg[:HEADER_SIZE])])
print(f"{sock_dict[reader]} >> {client_msg[HEADER_SIZE : HEADER_SIZE + int(client_msg[:HEADER_SIZE])]}")
client_msg = client_msg[HEADER_SIZE + int(client_msg[:HEADER_SIZE]) : ]
for client in sock_list:
if client is server or client is reader:
continue
else:
broadcast_message(client, broadcast_msg)
except:
continue
Client.py
import sys
import select
import socket
import msvcrt
IP_ADDR = socket.gethostbyname(socket.gethostname())
PORT = 5555
HEADER_SIZE = 10
class Connection():
def __init__(self, default = (IP_ADDR, PORT)):
self.client_conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print(f"Trying to connect to {default[0]} : {default[1]}")
self.client_conn.connect(default)
print("Connection succesful!")
username = input("Enter your username : ")
username = f'{len(username) :< {HEADER_SIZE}}' + username
self.client_conn.send(username.encode("utf-8"))
def fileno(self):
return self.client_conn.fileno()
def on_read(self):
msg = self.client_conn.recv(1024).decode("utf-8")
self.decode_message(msg)
def decode_message(self, msg):
while len(msg):
username = msg[HEADER_SIZE : HEADER_SIZE + int(msg[: HEADER_SIZE])]
msg = msg[HEADER_SIZE + int(msg[: HEADER_SIZE]) : ]
user_msg = msg[HEADER_SIZE : HEADER_SIZE + int(msg[: HEADER_SIZE])]
msg = msg[HEADER_SIZE + int(msg[: HEADER_SIZE]) : ]
print(f"{username} >> {user_msg}")
class Input():
def __init__(self, client):
self.client = client.client_conn
def fileno(self):
return sys.stdin.fileno()
def on_read(self):
#msg = sys.stdin.readline()[:-1]
msg = input("[:] >> ")
msg_len = len(msg)
msg = f'{msg_len :< {HEADER_SIZE}}' + msg
self.client.send(msg.encode("utf-8"))
connection = Connection()
read_input = Input(connection)
while True:
readers, _, _ = select.select([connection], [], [], 1)
if(msvcrt.kbhit()):
readers.append(read_input)
for reader in readers:
reader.on_read()
I have written a program that collects data from packets in iterations. Until a couple of days ago it worked fine.
EDIT: SOLVED. I saved IP as a constant and it overwrote IP.
from scapy.all import *
import requests
import socket
ROUND = 2
IP = 'localhost'
PORT = 80
SERVER_ADDRESS = (IP,PORT)
def get_packet_size(packet):
return len(packet)
def find_port(packet,ip):
if packet[IP].dst == ip:
if TCP in packet:
return packet[TCP].sport
else:
return packet[UDP].sport
else:
if UDP in packet:
return packet[TCP].dport
else:
return packet[UDP].dport
def check_traffic(packet , ip):
if packet[IP].dst == ip:
return False
else:
return True
def find_country(packet, ip):
request = "http://freegeoip.net/json/"+ip
response = requests.get(request)
real_response = response.text
real_response = real_response.split(",")
country_full = real_response[2]
country_full = country_full.split(":")
country = country_full[1]
country = country[1:len(country) - 1]
print(country)
return str(country)
def find_ip(packet):
name = socket.gethostname()
ip_of_agent = socket.gethostbyname(name)
if(packet[IP].dst != ip_of_agent):
return packet[IP].dst
else:
return packet[IP].src
def work_on_packets(packets):
packet_dic = {}
#ip_dic = []
i = 0 # num of packet in iteration.
for packet in packets:
print("\n")
packet_ip = find_ip(packet)
print(packet_ip)
country = find_country(packet,packet_ip)
print(country)
is_coming_traffic = check_traffic(packet,packet_ip) # True if coming , False if outer traffic.
port = find_port(packet,packet_ip)
print(port)
packet_size = get_packet_size(packet)
print(packet_size)
packet_dic["Packet "+str(i)] = [packet_ip,country,is_coming_traffic,port,packet_size]
i = i + 1
#send_data(packet_dic)
def is_IP(packet):
return ((UDP in packet or TCP in packet) and IP in packet)
def main():
print("Starting sniff..")
while(True):
packets = sniff(lfilter = is_IP )
work_on_packets(packets)
main()
But right now it just doesn't work. The output is always like this,nothing more:
WARNING: No route found for IPv6 destination :: (no default route?). This affects only IPv6
Starting sniff..
What could be the problem behind it? any help is great!
It's just a warning telling you that you don;t have any default routes for IPV6 and is totally normal for systems that do not have IPV6. This should not affect your program for IPV4 packets.
Here's how you can disable it
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
When I run the admin client after connecting some clients, my admin returns the ip addresses and port numbers fine. If i close the admin and rerun it nothing happens. This has me baffled. I am unsure why it is doing this
#Admin Client
from functools import partial
import ssl
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ts = ssl.wrap_socket(s, certfile="100298750.crt",
keyfile="100298750.key",
ca_certs="5cc515-root-ca.cer")
ts.connect(('192.168.0.5', 4001))
ts.send("Hello\r\n".encode())
if ts.recv(80).decode() == "Admin-Greetings\r\n":
print("The players currently online are:\n")
ts.send("Who\r\n".encode())
for data in iter(partial(ts.recv, 1000), b''):
print(data.decode())
ts.close()
Server
import threading
import socket
import math
import random
import ssl
addressList = []
def within(guess,goal,n):
absValue = abs(guess - goal)
if absValue <= n:
return True
else:
return False
def HandleAdmin(adminSocket,):
while True:
global addressList
(c,a) = adminSocket.accept()
ts = ssl.wrap_socket(c, certfile="5cc515_server.crt",
keyfile="5cc515_server.key",
server_side=True,
cert_reqs=ssl.CERT_REQUIRED,
ca_certs="5cc515-root-ca.cer")
if ts.recv(80).decode() == 'Hello\r\n':
ts.send('Admin-Greetings\r\n'.encode())
if ts.recv(80).decode() == 'Who\r\n':
for i in addressList:
ts.send(i.encode())
ts.close()
return
def HandleClient(c,a):
global addressList
address, port = a
address = str(address) + ' ' + str(port) + '\r\n'
addressList.append(address)
scoreCount = 0
guess = 0
if(c.recv(80).decode()) == 'Hello\r\n':
c.send('Greetings\r\n'.encode())
goal = random.randrange(1,21)
while guess!= goal:
guess =c.recv(80).decode()
guess = int(guess[7:len(guess)-2])
if guess == goal:
c.send('Correct\r\n'.encode())
addressList.remove(address)
c.close()
elif within(guess, goal, 2) == True:
c.send('Close\r\n'.encode())
else:
c.send('Far\r\n'.encode())
else:
c.close()
return
clientSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
clientSocket.bind(("192.168.0.5",4000))
clientSocket.listen(5)
adminSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
adminSocket.bind(("192.168.0.5",4001))
adminSocket.listen(5)
handleAdminThread = threading.Thread(target = HandleAdmin,
args = (adminSocket,))
handleAdminThread.start()
while True:
(c,a) = clientSocket.accept()
clientThread = threading.Thread(target = HandleClient, args = (c,a))
clientThread.start()
If i close the admin and rerun it nothing happens. This has me
baffled. I am unsure why it is doing this
It is simply doing this because the HandleAdmin() server thread code has the line
return
at the end of its loop and thus exits after one run. Drop it, and it is alright.
hi I want to create chat server with diesel . I use this code for running simple chat server :
from diesel import Application, Service, until_eol, fire, wait
def chat_server(addr):
my_nick = (yield until_eol()).strip()
while True:
my_message, other_message = yield (until_eol(), wait('chat_message'))
if my_message:
yield fire('chat_message', (my_nick, my_message.strip()))
else:
nick, message = other_message
yield "<%s> %s\r\n" % (nick, message)
app = Application()
app.add_service(Service(chat_server, 8000))
app.run()
but when I try to telnet this server , telnet Connection closed by foreign host.
[nima#ca005 Desktop]$ telnet localhost 8000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Connection closed by foreign host.
when I remove yield from code I have no problem with connectiong to server.
def chat_server(addr):
my_nick = until_eol().strip()
while True:
message = diesel.until_eol()
shouted_message = my_nick + ":" + message
diesel.send(shouted_message)
my_message = until_eol()
other_message = wait('chat_message')
if my_message:
fire('chat_message', (my_nick, my_message.strip()))
what is wrong with this code?
Maybe something like this. It mightn't work straight away as I am unfamiliar with how diesel works.
import StringIO
import socket
import threading
from diesel import Application, Service, until_eol, fire, wait
class socket_thread(threading.Thread):
def __init__(self, line_filter = None):
threading.Thread.__init__(self)
self.daemon = True
self.lock = threading.Lock()
self.event = threading.Event()
self.event.clear()
self.buffer = StringIO.StringIO()
if(line_filter == None):
self.line_filter = lambda x: x
else:
self.line_filter = line_filter
def run(self):
message = True
while message:
message = diesel.until_eol()
self.lock.acquire()
self.buffer.write(message)
self.lock.release()
self.event.set()
def readlines(self):
self.lock.acquire()
self.buffer.seek(0)
raw_lines = self.buffer.readlines()
self.buffer.truncate(0)
self.lock.release()
lines = map(self.line_filter, raw_lines)
return lines
def chat_server(addr):
server_recv = socket_thread()
my_nick = until_eol().strip()
data = []
server_recv.start()
while True:
server_recv.event.wait()
data = server_recv.readlines()
if(data):
shouted_message = my_nick + ":" + data
diesel.send(shouted_message)
server_recv.event.clear()
my_message = until_eol()
other_message = wait('chat_message')
if my_message:
fire('chat_message', (my_nick, my_message.strip()))
app = Application()
app.add_service(Service(chat_server, 8000))
app.run()
I found the right code here :
# vim:ts=4:sw=4:expandtab
'''Simple chat server.
telnet, type your name, hit enter, then chat. Invite
a friend to do the same.
'''
from diesel import Application, Service, until_eol, fire, first, send
def chat_server(addr):
my_nick = until_eol().strip()
while True:
evt, data = first(until_eol=True, waits=['chat_message'])
if evt == 'until_eol':
fire('chat_message', (my_nick, data.strip()))
else:
nick, message = data
send("<%s> %s\r\n" % (nick, message))
app = Application()
app.add_service(Service(chat_server, 8000))
app.run()
I try to make two servers in a file, but they are fighting each other visibly
have anyone an idea to make them peace ?
here is my code :
# -*- coding: utf-8 -*-
import socket
import sys
import re
import base64
import binascii
import time
import zlib
import sys
import StringIO
import contextlib
import smtplib
from threading import Thread
"""
Thanks to :
People from irc :
Flox,Luyt
People from stack Overflow :
Philippe Leybaert,Platinum Azure,methodin,Suresh Kumar,S.Lott,MatTheCat,
kevpie,Ignacio Vazquez-Abrams,adamk,Frédéric Hamidi,THC4k,THC4k,Blam
"""
def sendmail(exp,dest,msg):
server = dest.split("#")[1]
s = smtplib.SMTP("localhost")
s.sendmail(exp,dest,msg)
#contextlib.contextmanager
def stdoutIO(stdout=None):
old = sys.stdout
if stdout is None:
stdout = StringIO.StringIO()
sys.stdout = stdout
yield stdout
sys.stdout = old
class Serversmtp(Thread):
def __init__self(self):
Thread.__init__(self)
def run(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_address = ('localhost', 25)
print >>sys.stderr, 'starting up on %s port %s' % server_address
self.sock.bind(server_address)
# Listen for incoming connections
self.sock.listen(1)
self.message = ""
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection, client_address = self.sock.accept()
try:
print >>sys.stderr, 'connection from', client_address
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(1024)
print >>sys.stderr, 'received "%s"' % data
if data:
self.message = self.traitement(data)
connection.sendall(self.message)
connection.close()
connection, client_address = self.sock.accept()
else:
print >>sys.stderr, 'no more data from', client_address
break
finally:
# Clean up the connection
connection.close()
self.sock.close()
class Pages :
def root(self,cgi=None):
return """eNqtVV1zqkgQfedX3MrrbNVREBnu5ubWCCoajPiRaHyTxEGNiAKC8uu3B7Nb+7JvO1QNNAOnT5/u
6Xnc5vHhSXsMk8/bk5bv7tdjmNK7XRz9yNKPXw+f63z9cxevow12H8mf4TrbtFt/CCE6QnRFl2Z1
H4hOoh57EU2OmsRETQPx9/p/D+3fhhXMLRhVrw07yC/ANPSuaOi6BTavihB2UZiwrW1D2sNNp8KL
lwhUNheFLaRwoQVeJtDotUXAa0AUlYUmMwzw0YlV6KVeievixiUPM8zhndMrOexaBWhYyPn5hKqn
C3BLi0oPQWvgojJtAmSbyMXE+BLEIOMFD5N8j65/NFDeTAIMcunDtXxycKnsgBdnJsFxVMCWZhf2
83ZqYPz+Tgz7PVFwvlWAA+GgaloiQINhj5d2OELpNCxw5yotOFlgoYyZXXBxvqSYpW6oESKDokxr
b6vuAdVsSAyt/cRFUDsYdzqSMznx6CMDsN0TB29lIwJMXUkOmi1ykF58aM/n4wL2MeOKLYG2xvsl
KtZ3JTe/SNRgUJIE+pAYs61ykHRJAsc6FSTEpRaOwV6WrGClZmz2OGTYgKWVjftgqNrQ9Xgm+XlP
jMbDEWXtMiHG5q70yUFE9q0nAjaezXwc31otWEOmvRUQX30LVp4GKjuQsNW9DT+FfkmmBc8VYDB8
V4BzJcFXqSTgZOvPZNtbiiA5fB01tKdvXsA2s2iPuBtNAS8xFLnCgjmutmj210MCPNAP49UHJeWy
pJBbtW0OyNYDIbmtGGvjAZVBe7voSfYxv7o4xbYDq73bBncNmYqbH9cFuPykH15WVJfVZkWMjJiy
HgwnHQr5lQBb2r6mnNGLtickk8udRDNtZxSqktDktBOMlEVgxk4vFLaBONz1cLs5KuQ4CjA+EWq1
WWhK1AM9j09dAmSkie1sqZCtjRfW2Sigc0pSvigTEvaVRDeXE5JgxMz7Oguz1REDT3xqhPimRDwo
D6bK2nroSJ6v5inc2+W5ri2gTnTjHJMEB3KI55WYo3iLHPDdZCHvjKlo98AtOl3B+/0PH93Z+opr
N8oL3uuOKgjhb1GKTlMSGlU+UJECJh8D/eXEx63/ToDTtSgw1vYHeRe5Hvbk1TbQEW5DAZDyrggM
AvQqsoUpyc7T728L2jpMD505AVJE3I5JM3QWVNmNM3PxnTy1taZfYYSyK5ikbkJsxMQzUY4EV91l
Q8UpXFm3jeDePS6Dl4lGGiwJcPROaS/6A2Lvx8Z3WTQ/5zrKZGSCABTD0mM1Y+VAhiqCjGyn9d2+
SDPqX8wPq4DFyxtV8mvZhd3PtlRYSlQLxKhKUCrAzyVE5LdVyATofEugK9ui7lF32oja8f8x/mnb
d8Bfvx6e7kfHb+2U7o75j4c8yZMH9qDePmi/nzTtEfej5hH1yfMXx7rT9A=="""
def favico(self):
return """eNqdk39MVWUYx99zDrZkJJc/dGtqsVZKFmttFhcuF0wXC1bTZmq0qVuWa8t+/NXPW1MQCk3FMBKs
LNauoq6AAr2zsFLLHAN1YQXJryzJewXuhV29HO759JyX//uj9933vOe8e7/f5/k+73OUMmR6PEqe
meq5FKXmKKWyBLIlO9P7/zUiEzaB02GWt43ycHOUx2St6YwTtxP0DZ6n+LV5LH5DURgwWRJQ5L+p
eEi+Xa4zZbP+aD9pByLMaR5jdkuUuV9NcNuhKIFTI4DD0bON3P+Kha/coLDMouAtRYHwl72u6IvE
mNvwG57QddJCUdJbY6S3jGmN+w5fYTwhCnackor55FZK3AqTfFmXbDbxSx4T9g1ygh2or0cxTzuk
nrSZ2R5HHbpKSVMvjuPAlMOq3XexuErh26HwC3/ZlhmShwFJOPfPON6mTlKb+lGtf2J+McSixov8
Hom6VAaGf6Ww8hZyq8X7exb+KpOCCvGwRXHueJDkSFj77B6bpOnSMLVdfVwdv4477KlJXggWs2iH
gbdG4otG7nbx8K5oicbO4jv4eJ2XlrdX8131i4z0dIlSUqZDOBbm+YNFZAs3v1a4NdPw7xJsE2xV
NJQu5PNV8/ik5Gb2PpJBdLhfe74cGeTx+gVk75F4H5r4BF55970vddtl4JccvFKPg6tn89FyD8GX
ltLesFX7tSXvn3tOcPurJg/sU+TUCeol3z2GhteNv92g4B2D/esWcrH9CI7UMREbpe/Ep1wb6tEe
6o5VcG+ZxKy3yNtrkSMecgV5u6UPxMdS4V8b7NW1i0eHad2UxfEnFKG1s7jcFdL7+5rryHx5Pjkf
SMxaS/t/sGom2c/mkX7PNvf6NC40lhFaqTj7TArfPmlyprpU58ANyLr7J2669QcyFjSTkdnGDI/0
izmIMrqF7PYHtAd8/LhWeBtNTj1l0rlzja6DO1asvESKmpDzYKmkrOPS+39hmT3Td2zbtG26kzMb
FF0bFd+XKi58We6mr3uvqGgAQyVQ1hSGkRCNMdEIi0a/2yDa57HyFYTWKDo2mHzz9Cxif/+h76L7
lzipaVfkbBLLcITnxo9LPhHxMKD/QeQfHOrtILg+k88eTeH8kUqxlGQ0miCv8KT2aZqTWsNU03yl
RjR3s6H+93C5/wIoQoi6"""
class Serverhttp(Thread):
def __init__(self):
Thread.__init__(self)
self.Pages = Pages()
self.GET = re.compile("GET.*?HTTP")
self.POST = re.compile("POST.*?HTTP")
self.balisep = re.compile("<\?.*\?>",re.DOTALL)
def run(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_address = ('localhost', 41000)
print >>sys.stderr, 'starting up on %s port %s' % server_address
self.sock.bind(server_address)
# Listen for incoming connections
self.sock.listen(1)
self.message = ""
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection, client_address = self.sock.accept()
try:
print >>sys.stderr, 'connection from', client_address
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(1024)
print >>sys.stderr, 'received "%s"' % data
if data:
self.message = self.traitement(data)
connection.sendall(self.message)
connection.close()
connection, client_address = self.sock.accept()
else:
print >>sys.stderr, 'no more data from', client_address
break
finally:
# Clean up the connection
connection.close()
self.sock.close()
def decompress_img(self,img):
img = zlib.decompress(base64.decodestring(img))
return img
def decompress_html(self,html) :
page = "HTTP/1.0 200 OK\r\nContent-type:text/html;charset=utf8\r\n\r\n"
page+=zlib.decompress(base64.decodestring(html))
commands = self.balisep.findall(page)
print commands
for c in commands :
command = c.replace("<? ","")
command = c.replace("<?","")
command = command.replace(" ?>","")
command = command.replace("?>","")
print command
with stdoutIO() as s:
exec(command)
page = page.replace(c,s.getvalue())
return page
def traitement(self,data):
url = self.POST.findall(data)
print url
print len(url)
url = self.GET.findall(data)
print url
url = url[0].replace("GET","")
url = url.replace("POST","")
url = url.replace("HTTP","")
url = url.replace(" ","")
print url
if url == "/favicon.ico":
return self.decompress_img(self.Pages.favico())
else :
return self.decompress_html(self.Pages.root())
if __name__ == "__main__":
swww = Serverhttp()
swww.start()
ssmtp = Serversmtp()
ssmtp.start()
sendmail("test#test.com","b#gmail.com","hello")
print "toto"
Regards and thanks all people
it was better to use : SocketServer.BaseRequestHandler with handler
and one for each server :
as seen here :
# MetaProject v 0.21
# -*- coding: utf-8 -*-
import socket
import sys
import re
import base64
import binascii
import time
import zlib
import sys
import StringIO
import contextlib
import smtplib
import threading
import SocketServer
SocketServer.TCPServer.allow_reuse_address = True
"""
Thanks to :
People from irc :
Flox,Luyt
People from stack Overflow (http://stackoverflow.com/):
Philippe Leybaert,Platinum Azure,methodin,Suresh Kumar,S.Lott,MatTheCat,
kevpie,Ignacio Vazquez-Abrams,adamk,Frédéric Hamidi,THC4k,THC4k,Blam,bstpierre
"""
def sendmail(exp,dest,msg):
server = dest.split("#")[1]
s = smtplib.SMTP("localhost")
s.sendmail(exp,dest,msg)
#contextlib.contextmanager
def stdoutIO(stdout=None):
old = sys.stdout
if stdout is None:
stdout = StringIO.StringIO()
sys.stdout = stdout
yield stdout
sys.stdout = old
class Serversmtp(SocketServer.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(1024)
socket = self.request
print "%s wrote:" % self.client_address[0]
self.data = self.traitement(self.data)
socket.sendto(self.data, self.client_address)
def traitement(self,data):
return "toto"
class Pages :
def __init__(self):
self.balisep = re.compile("<\?.*\?>",re.DOTALL)
def root(self,cgi=None):
return self.decompress_html("""eNqzySjJzbHjsknKT6m04yrJhECbpCKgWGZuukJxUbKtUlpiWWZyfp4ekFCyg8jZcxUUZeaVKCiV
5JfkK2krgUSVuOztuLhs9CFm2eiDjQYAG5wecg==""")
def faviconico(self):
return self.decompress_img("""eNqdk39MVWUYx99zDrZkJJc/dGtqsVZKFmttFhcuF0wXC1bTZmq0qVuWa8t+/NXPW1MQCk3FMBKs
LNauoq6AAr2zsFLLHAN1YQXJryzJewXuhV29HO759JyX//uj9933vOe8e7/f5/k+73OUMmR6PEqe
meq5FKXmKKWyBLIlO9P7/zUiEzaB02GWt43ycHOUx2St6YwTtxP0DZ6n+LV5LH5DURgwWRJQ5L+p
eEi+Xa4zZbP+aD9pByLMaR5jdkuUuV9NcNuhKIFTI4DD0bON3P+Kha/coLDMouAtRYHwl72u6IvE
mNvwG57QddJCUdJbY6S3jGmN+w5fYTwhCnackor55FZK3AqTfFmXbDbxSx4T9g1ygh2or0cxTzuk
nrSZ2R5HHbpKSVMvjuPAlMOq3XexuErh26HwC3/ZlhmShwFJOPfPON6mTlKb+lGtf2J+McSixov8
Hom6VAaGf6Ww8hZyq8X7exb+KpOCCvGwRXHueJDkSFj77B6bpOnSMLVdfVwdv4477KlJXggWs2iH
gbdG4otG7nbx8K5oicbO4jv4eJ2XlrdX8131i4z0dIlSUqZDOBbm+YNFZAs3v1a4NdPw7xJsE2xV
NJQu5PNV8/ik5Gb2PpJBdLhfe74cGeTx+gVk75F4H5r4BF55970vddtl4JccvFKPg6tn89FyD8GX
ltLesFX7tSXvn3tOcPurJg/sU+TUCeol3z2GhteNv92g4B2D/esWcrH9CI7UMREbpe/Ep1wb6tEe
6o5VcG+ZxKy3yNtrkSMecgV5u6UPxMdS4V8b7NW1i0eHad2UxfEnFKG1s7jcFdL7+5rryHx5Pjkf
SMxaS/t/sGom2c/mkX7PNvf6NC40lhFaqTj7TArfPmlyprpU58ANyLr7J2669QcyFjSTkdnGDI/0
izmIMrqF7PYHtAd8/LhWeBtNTj1l0rlzja6DO1asvESKmpDzYKmkrOPS+39hmT3Td2zbtG26kzMb
FF0bFd+XKi58We6mr3uvqGgAQyVQ1hSGkRCNMdEIi0a/2yDa57HyFYTWKDo2mHzz9Cxif/+h76L7
lzipaVfkbBLLcITnxo9LPhHxMKD/QeQfHOrtILg+k88eTeH8kUqxlGQ0miCv8KT2aZqTWsNU03yl
RjR3s6H+93C5/wIoQoi6""")
def toto(self):
return self.decompress_html("""eNqzySjJzbHjsknKT6m04yrLLy1WSC1JLVZIVCjJL8nnstGHSNjog9UBAGolDzo=""")
def p404(self):
return self.decompress_html("""eNqzySjJzbHjsknKT6m04zIxMFFIScwrVihJVEhLTE5VUOSy0YdI2eiDVQIAZBgOeA==""")
def decompress_img(self,img):
img = zlib.decompress(base64.decodestring(img))
return img
def decompress_html(self,html) :
page = "HTTP/1.0 200 OK\r\nContent-type:text/html;charset=utf8\r\n\r\n"
page+=zlib.decompress(base64.decodestring(html))
commands = self.balisep.findall(page)
print commands
for c in commands :
command = c.replace("<? ","")
command = c.replace("<?","")
command = command.replace(" ?>","")
command = command.replace("?>","")
print command
with stdoutIO() as s:
exec(command)
page = page.replace(c,s.getvalue())
return page
class Serverhttp(SocketServer.BaseRequestHandler):
def handle(self):
self.Pages = Pages()
self.GET = re.compile("GET.*?HTTP")
self.POST = re.compile("POST.*?HTTP")
self.data = self.request.recv(1024)
socket = self.request
print "%s wrote:" % self.client_address[0]
self.data = self.traitement(self.data)
socket.sendto(self.data, self.client_address)
def traitement(self,data):
url = self.POST.findall(data)
url = self.GET.findall(data)
url = url[0].replace("GET","")
url = url.replace("POST","")
url = url.replace("HTTP","")
url = url.replace(" ","")
url = re.sub(r"^/","",url)
url = re.sub(r"\.","",url)
if url != "":
urls = url.split("/")
if len(urls) != 0 :
print urls
url = urls[0]
print "url %s"%url
if url == "" :
return self.Pages.root()
elif url in dir(self.Pages) and url != "":
return getattr(self.Pages,url)()
else :
return self.Pages.p404()
def serve_thread(host, port):
if port == 4242 :
server = SocketServer.TCPServer((host, port), Serverhttp,bind_and_activate=True)
elif port == 25 :
server = SocketServer.TCPServer((host, port), Serversmtp,bind_and_activate=True)
server.serve_forever()
if __name__ == "__main__":
threading.Thread(target=serve_thread,args=('localhost', 4242)).start()
threading.Thread(target=serve_thread,args=('localhost', 25)).start()
print "toto"