1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
#! /usr/bin/python
# Copyright 2013 Linaro Limited
# Author Matt Hart <matthew.hart@linaro.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
import SocketServer
import logging
import socket
class ListenerServer(object):
servers = []
def __init__(self, config):
logging.getLogger().name = "ManagementServer"
logging.getLogger().setLevel(config["logging_level"])
self.management_server = TCPServer((config["hostname"], config["mgmt-port"]), TCPRequestHandler)
# for portnum in range(config["port-start"], config["port-end"]):
# self.servers.append(TCPServer((config["hostname"], portnum), TCPRequestHandler))
# logging.info("listening on %s:%s" % (config["hostname"], portnum))
def start(self):
logging.info("Starting the Management Server")
self.management_server.serve_forever()
# for server in self.servers:
# server.serve_forever()
class TCPRequestHandler(SocketServer.BaseRequestHandler):
#"One instance per connection. Override handle(self) to customize action."
def handle(self):
logging.getLogger().name = "TCPRequestHandler"
ip = self.client_address[0]
logging.debug(self.client_address)
try:
data = self.request.recv(4096).strip()
socket.setdefaulttimeout(2)
try:
request_host = socket.gethostbyaddr(ip)[0]
except socket.herror as e:
logging.debug("Unable to resolve: %s error: %s" % (ip, e))
request_host = ip
logging.info("Received a request from %s: '%s'" % (request_host, data))
self.request.sendall("ack\n")
except Exception as e:
logging.debug(e)
self.request.sendall("nack\n")
self.request.close()
class TCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
allow_reuse_address = True
daemon_threads = True
pass
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
logging.getLogger().setLevel(logging.DEBUG)
logging.debug("Executing from __main__")
starter = {"hostname": "0.0.0.0",
"port-start": 40001,
"port-end": 41000,
"mgmt-port": 40000,
"logging_level": logging.DEBUG}
ss = ListenerServer(starter)
ss.start()
|