1
0
Fork 0

- cleaned class argparser

- commented and cleaned asrc-server.py
- renamed includes/content.py to includes/comm.py
- renamed class content to comm
- made some vars (aliases, server_version, protocol_version, verbiosity) global in class comm
- added init() to class comm for setting lobal vars
- moved motd() from asrc-server-py to class comm
- conformed comm.motd() to reference
- added comm.header() for building the headers
- added includes/statuscodes.py with class statuscodes with dict description for storing the status codes and their description
- added docstrings
This commit is contained in:
fanir 2013-04-26 12:55:37 +02:00
parent fbb4653740
commit 1207c6b225
6 changed files with 306 additions and 297 deletions

View file

@ -25,7 +25,7 @@
# aSRC (Aliased Server Remote Control) # aSRC (Aliased Server Remote Control)
# - SERVER - # - SERVER -
# #
# program version: 0.0.0.20130424 # program version: 0.0.0.20130426
# protocol version: 0.2.20130423 # protocol version: 0.2.20130423
# #
# #
@ -35,243 +35,175 @@
import sys, os, socket, socketserver, threading, time import sys, os, socket, socketserver, threading, time
def motd():
return MOTD
#def content(client_address, data):
#ret = ""
#ret = ret +\
#"{BEGIN}\n"\
#"asrcp" + ProtocolVersion + "\n"
## Look if the received message is an
## valid alias or a predefined command
## if it's 'version', return the server and protocol version
#if data == "version":
#if VERBOSITY >= 2: print("Got valid service command from"
#+ str(client_address) + ": ", data)
#ret = ret +\
#"202 Valid Service Command\n"\
#"002 Version\n"\
#"ServerVersion:" + ServerVersion + "\n"\
#"ProtocolVersion:" + ProtocolVersion + "\n"
## if it's 'help', give a little help
#elif data == 'help':
#if VERBOSITY >= 2: print("Got valid command from"
#+ str(client_address) + ": ", data)
## send status code
#ret = ret + "202 Valid Service Command\n\n"
## send the list of aliases
#ret = ret + "Aviable aliases:\n"
#for i in aliases.keys():
#ret = ret + str(i) + "\n"
## if it's a valid userdefined command
#elif data in aliases:
## send status code
#ret = ret + "201 Valid Command\n\n"
## ohmagawd! a debug message!!1!
#if VERBOSITY >= 2: print("Got valid command from"
#+ str(client_address) + ": ", data)
## execute the aliased command
#g_dict, l_dict = {}, {}
#exec(str(aliases[data]), g_dict, l_dict)
## send may contain data to send to the client
#if l_dict["send"]:
#content = str(l_dict["send"]).replace('{', '\{')
#content = content.replace('}', '\}')
#ret = ret + content + "\n"
## ALL IS LOST!!1! this has to be invalid!
#else:
## send status code
#ret = ret + "203 Invalid Command\n"
#if VERBOSITY >= 2: print("Got invalid command from",
#str(client_address), ": ", data)
#ret = ret + "{END}\n"
#return ret
class ThreadedRequestHandler(socketserver.StreamRequestHandler): class ThreadedRequestHandler(socketserver.StreamRequestHandler):
def handle(self): def handle(self):
"""
Handles incoming connections
"""
# Set time for timeout in seconds # Set time for timeout in seconds
self.timeout = TIMEOUT self.timeout = TIMEOUT
# Print a line with the adress of the connected client # Print a line with the adress of the connected client
if VERBOSITY >=3: if VERBOSITY >=3:
print("Client connected: " + str(self.client_address)) print("Client connected: " + str(self.client_address))
# send header line 1 # send motd
self.request.sendall(bytes self.request.sendall(comm.motd(MOTD) + "\n", ENCODING))
("asrpc " + ProtocolVersion + "\n", ENCODING))
# send motd # Receive data
self.request.sendall(bytes(motd() + "\n", ENCODING)) self.data = str(self.rfile.readline().strip(), ENCODING)
# Receive data # content handler
self.data = str(self.rfile.readline().strip(), ENCODING) self.request.sendall(bytes(
comm.handler(str(self.client_address), self.data), ENCODING))
# content handler
self.request.sendall(bytes(
content.handler(str(self.client_address), self.data, aliases,
ServerVersion, ProtocolVersion, VERBOSITY), ENCODING))
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
pass pass
def main(): def main():
global VERBOSITY, HOST, PORT, TIMEOUT, ENCODING # import global settings
global VERBOSITY, HOST, PORT, TIMEOUT, ENCODING
from include import argparser, content from include import argparser, comm
parser = argparser comm.init(ServerVersion, ProtocolVersion, VERBOSITY, aliases)
args = parser.parse(ServerVersion, ProtocolVersion)
if os.path.exists("pid"): # parse arguments
if args.delete_pid_file: os.remove("pid") parser = argparser
elif args.allow_multiple_instances: pass args = parser.parse(ServerVersion, ProtocolVersion)
else:
print(
"\npid file already exists\n"\
"If the server didn't shut down correctly, just delete this file "\
"or pass -n\n"\
"If you want to start multiple instances, pass -m\n")
return 1
print(args) # look for pid file
if os.path.exists("pid"):
# remove, ...
if args.delete_pid_file: os.remove("pid")
# ... ignore ...
elif args.allow_multiple_instances: pass
# ... or exit
else:
print(
"\npid file already exists\n"\
"If the server didn't shut down correctly, "\
"just delete this file or pass -n\n"\
"If you want to start multiple instances, pass -m\n")
return 1
if args.host: HOST = args.host # set settings if command line options are given
if args.port: PORT = args.port if args.host: HOST = args.host
if args.timeout: TIMEOUT = args.timeout if args.port: PORT = args.port
if args.encoding: ENCODING = args.encoding if args.timeout: TIMEOUT = args.timeout
if args.verbosity: VERBOSITY = args.verbosity if args.encoding: ENCODING = args.encoding
if args.verbosity: VERBOSITY = args.verbosity
# write pid file # write pid file
pidf = open("pid", 'w') pidf = open("pid", 'w')
pidf.write(str(os.getpid())) pidf.write(str(os.getpid()))
pidf.close() pidf.close()
print("aSRC Server\n"\ print("aSRC Server\n"\
"Server version: " + ServerVersion + "\n"\ "Server version: " + ServerVersion + "\n"\
"Protocol version: " + ProtocolVersion + "\n\n"\ "Protocol version: " + ProtocolVersion + "\n\n"\
"To stop the server, press Ctrl-C\n") "To stop the server, press Ctrl-C\n")
try: try:
if VERBOSITY >= 1: print("Initializing server...") if VERBOSITY >= 1: print("Initializing server...")
# Create server # Create server
server = ThreadedTCPServer((HOST, PORT), ThreadedRequestHandler) server = ThreadedTCPServer((HOST, PORT), ThreadedRequestHandler)
if VERBOSITY >= 1: print("Starting server on", if VERBOSITY >= 1: print("Starting server on",
server.server_address[0], "port", server.server_address[1], "...") server.server_address[0], "port", server.server_address[1], "...")
# Start a thread with the server -- that thread will then start one # Start a thread with the server -- that thread will then start one
# more thread for each request # more thread for each request
ServerThread = threading.Thread(target = server.serve_forever) ServerThread = threading.Thread(target = server.serve_forever)
# Exit the server thread when the main thread terminates # Exit the server thread when the main thread terminates
ServerThread.daemon = True ServerThread.daemon = True
ServerThread.start() ServerThread.start()
while True:
time.sleep(10)
except KeyboardInterrupt: while True:
print("\nGot Ctrl-C, shutting down server...") time.sleep(10)
try: # exit if Ctrl-C is pressed
server.shutdown() except KeyboardInterrupt:
os.remove("pid") print("\nGot Ctrl-C, shutting down server...")
except: print("Failed to shutdown server correctly, "\
"socket may be still in use or wasn't even started:",
sys.exc_info())
#except:
# print("\nAn error occured:\n", sys.exc_info(), "\n")
if VERBOSITY >= 3: input("Press Enter to continue\n") try:
return 0 server.shutdown()
os.remove("pid")
except: print("Failed to shutdown server correctly, "\
"socket may be still in use or wasn't even started:",
sys.exc_info())
#except:
# print("\nAn error occured:\n", sys.exc_info(), "\n")
if VERBOSITY >= 3: input("Press Enter to continue\n")
return 0
if __name__ == '__main__': if __name__ == '__main__':
ServerVersion = "0.0.0" ServerVersion = "0.0.0"
ProtocolVersion = "0.2" ProtocolVersion = "0.2"
############## ##############
# SETTINGS # # SETTINGS #
############## ##############
# IP or hostname (use 0.0.0.0 for all interfaces) and port, on which # IP or hostname (use 0.0.0.0 for all interfaces) and port, on which
# the server should listen # the server should listen
HOST = '127.0.0.1' HOST = '127.0.0.1'
PORT = 24642 PORT = 24642
# Timeout of a connection in seconds - still doesn't work obviously... # Timeout of a connection in seconds - still doesn't work obviously...
TIMEOUT = 15 TIMEOUT = 15
# Encoding to be used when communicating with a client # Encoding to be used when communicating with a client
ENCODING = 'utf-8' ENCODING = 'utf-8'
# Dictionary of aliases. Use python syntax. You can use # Dictionary of aliases. Use python syntax. You can use
# the variable send for text to send to the client. # the variable send for text to send to the client.
# #
# Shell commands can be executed with: # Shell commands can be executed with:
# import subprocess # import subprocess
# send = subprocess.check_output(["command", "arg", "somemorearg"]) # send = subprocess.check_output(["command", "arg", "somemorearg"])
# #
# You don't have to include sys, os, socket, socketserver, # You don't have to include sys, os, socket, socketserver,
# threading and time, through they are included already. # threading and time, through they are included already.
aliases = dict( aliases = dict(
who = ''' who = '''
import subprocess import subprocess
send = subprocess.check_output(["whoami"]) send = subprocess.check_output(["whoami"])
''', ''',
where = ''' where = '''
import subprocess import subprocess
send = subprocess.check_output(["pwd"]) send = subprocess.check_output(["pwd"])
''', ''',
uname = ''' uname = '''
import os import os
send = os.uname() send = os.uname()
''', ''',
date = ''' date = '''
import subprocess import subprocess
send = subprocess.check_output(["date"]) send = subprocess.check_output(["date"])
''', ''',
ping_fanir = ''' ping_fanir = '''
import subprocess import subprocess
send = subprocess.check_output(["ping", "-c 2", "fanir.de"]) send = subprocess.check_output(["ping", "-c 2", "fanir.de"])
''') ''')
# This is sent to the client after the connection is established # This is sent to the client after the connection is established
MOTD = "Welcome! This is only a test server, for developing purposes.\n"\ MOTD = "Welcome! This is only a test server, for developing purposes.\n"\
"Here (may) be more text..." "Here (may) be more text..."
# Verbosity of logging. # Verbosity of logging.
# Can be from 0 (only default output) to 3 (debug messages) # Can be from 0 (only default output) to 3 (debug messages)
VERBOSITY = 3 VERBOSITY = 3
############## ##############
main() main()

Binary file not shown.

View file

@ -1,2 +1,2 @@
from .argparser import argparser from .argparser import argparser
from .content import content from .comm import comm

View file

@ -1,78 +1,77 @@
# includes/argparser.py # includes/argparser.py
# #
# module version: 1.0.20130424 # module version: 1.0.20130425
# #
class argparser: class argparser:
def parse(program_version, protocol_version): def parse(program_version, protocol_version):
import argparse """
Parses comand line arguments
"""
parser = argparse.ArgumentParser( import argparse
description = "The server side of the "\
"aliased server remote control", parser = argparse.ArgumentParser(
add_help = False) description = "The server side of the "\
"aliased server remote control",
add_help = False)
parser.add_argument( parser.add_argument(
"--help", "--help",
action = "help", action = "help",
help = "show this help message and exit") help = "show this help message and exit")
parser.add_argument( parser.add_argument(
"--version", "--version",
action = "version", action = "version",
version = "Server version: " + program_version +\ version = "Server version: " + program_version +\
" / Protocol version: " + protocol_version) " / Protocol version: " + protocol_version)
grp_pid_file_failure = parser.add_mutually_exclusive_group() grp_pid_file_failure = parser.add_mutually_exclusive_group()
grp_pid_file_failure.add_argument( grp_pid_file_failure.add_argument(
"-n", "-n",
"--delete-pid-file", "--delete-pid-file",
action = "store_true", action = "store_true",
help = "deletes the pid file and starts the server") help = "deletes the pid file and starts the server")
grp_pid_file_failure.add_argument( grp_pid_file_failure.add_argument(
"-m", "-m",
"--allow-multiple-instances", "--allow-multiple-instances",
action = "store_true", action = "store_true",
help = "ignores the pid file and starts the server. "\ help = "ignores the pid file and starts the server. "\
"Will not create another pid file.") "Will not create another pid file.")
parser.add_argument( parser.add_argument(
"-v", "-v",
"--verbosity", "--verbosity",
type = int, type = int,
choices = range(0, 4), choices = range(0, 4),
# default = -1, help = "increase output verbosity. Can be from 0 "\
help = "increase output verbosity. Can be from 0 "\ "(only default output) to 3 (debug messages).")
"(only default output) to 3 (debug messages).")
parser.add_argument( parser.add_argument(
"-h", "-h",
"--host", "--host",
# default = -1, help = "IP or hostname (use 0.0.0.0 for all interfaces) on which "\
help = "IP or hostname (use 0.0.0.0 for all interfaces) on which "\ "the server should listen")
"the server should listen")
parser.add_argument( parser.add_argument(
"-p", "-p",
"--port", "--port",
# default = -1, help = "the port on which the server should listen")
help = "the port on which the server should listen")
parser.add_argument( parser.add_argument(
"-t", "-t",
"--timeout", "--timeout",
# default = -1, help = "timeout of a connection in seconds - still "\
help = "timeout of a connection in seconds - still "\ "doesn't work obviously...")
"doesn't work obviously...")
parser.add_argument( parser.add_argument(
"-e", "-e",
"--encoding", "--encoding",
# default = -1, help = "encoding to be used when communicating with clients")
help = "encoding to be used when communicating with clients")
return parser.parse_args() return parser.parse_args()

View file

@ -1,18 +1,59 @@
# includes/content.py # includes/comm.py
# #
# module version: 0.0.20130424 # module version: 0.0.20130426
# #
class content: import statuscodes
# handler the content
def handler(client_address, data, aliases, server_version, protocol_version, verbosity):
ret = ""
ret = ret +\ class comm:
aliases = dict()
server_version = ""
protocol_version = ""
verbosity = 0
# initializes global settings
def init(ServerVersion, ProtocolVersion, Verbosity, Aliases):
aliases = Aliases
server_version = ServerVersion
protocol_version = ProtocolVersion
verbosity = Verbosity
def header(statuscode, AdditionalHeaderLines = ""):
"""
returns the header
"""
ret =\
"{BEGIN}\n"\ "{BEGIN}\n"\
"asrcp" + protocol_version + "\n" "asrcp" + protocol_version + "\n"\
statuscode + " " + statuscodes.description[statuscodes] + "\n"\
"ServerVersion:" + server_version + "\n"
if AdditionalHeaderLines != "": ret += AdditionalHeaderLines + "\n"
ret += "\n\n"
return ret
# returns the motd
def motd(motd):
"""
builds and returns a motd package
"""
ret = motd
return ret
# handles the content
def command(client_address, data):
"""
processes a command
"""
ret = ""
# Look if the received message is an # Look if the received message is an
# valid alias or a predefined command # valid alias or a predefined command

37
include/statuscodes.py Normal file
View file

@ -0,0 +1,37 @@
class statuscodes:
description = dict(
# 000 - 400 server side
# 000 information
001 = "OK",
002 = "Version",
003 = "MOTD",
# 100 authentication and maintenance
101 = "Challenge",
102 = "Success",
103 = "Failure",
104 = "To Many Tries",
# 200 command
201 = "Valid",
202 = "Valid Service Command",
203 = "Invalid",
204 = "Failure",
205 = "Continue",
# 300 server
301 = "Unhandled Exception",
302 = "Shutting Down",
303 = "Restarting",
304 = "Encoding Error",
305 = "SSL Error",
# 500 - 900 client side
# 500 information
501 = "OK",
502 = "Version",
# 600 authentication and maintenance
601 = "Response",
602 = "Failure",
# 700 command
701 = "Reqiuest",
702 = "Cancel",
# 800 client
801 = "SSL Error"
)