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):
"""
# Set time for timeout in seconds Handles incoming connections
self.timeout = TIMEOUT """
# Print a line with the adress of the connected client # Set time for timeout in seconds
if VERBOSITY >=3: self.timeout = TIMEOUT
print("Client connected: " + str(self.client_address))
# Print a line with the adress of the connected client
# send header line 1 if VERBOSITY >=3:
self.request.sendall(bytes print("Client connected: " + str(self.client_address))
("asrpc " + ProtocolVersion + "\n", ENCODING))
# send motd
# send motd self.request.sendall(comm.motd(MOTD) + "\n", ENCODING))
self.request.sendall(bytes(motd() + "\n", ENCODING))
# Receive data
# Receive data self.data = str(self.rfile.readline().strip(), ENCODING)
self.data = str(self.rfile.readline().strip(), ENCODING)
# content handler
# content handler self.request.sendall(bytes(
self.request.sendall(bytes( comm.handler(str(self.client_address), self.data), ENCODING))
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
args = parser.parse(ServerVersion, ProtocolVersion) comm.init(ServerVersion, ProtocolVersion, VERBOSITY, aliases)
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( # look for pid file
"\npid file already exists\n"\ if os.path.exists("pid"):
"If the server didn't shut down correctly, just delete this file "\ # remove, ...
"or pass -n\n"\ if args.delete_pid_file: os.remove("pid")
"If you want to start multiple instances, pass -m\n") # ... ignore ...
return 1 elif args.allow_multiple_instances: pass
# ... or exit
print(args) else:
print(
if args.host: HOST = args.host "\npid file already exists\n"\
if args.port: PORT = args.port "If the server didn't shut down correctly, "\
if args.timeout: TIMEOUT = args.timeout "just delete this file or pass -n\n"\
if args.encoding: ENCODING = args.encoding "If you want to start multiple instances, pass -m\n")
if args.verbosity: VERBOSITY = args.verbosity return 1
# write pid file # set settings if command line options are given
pidf = open("pid", 'w') if args.host: HOST = args.host
pidf.write(str(os.getpid())) if args.port: PORT = args.port
pidf.close() if args.timeout: TIMEOUT = args.timeout
if args.encoding: ENCODING = args.encoding
print("aSRC Server\n"\ if args.verbosity: VERBOSITY = args.verbosity
"Server version: " + ServerVersion + "\n"\
"Protocol version: " + ProtocolVersion + "\n\n"\ # write pid file
"To stop the server, press Ctrl-C\n") pidf = open("pid", 'w')
pidf.write(str(os.getpid()))
try: pidf.close()
if VERBOSITY >= 1: print("Initializing server...")
# Create server print("aSRC Server\n"\
server = ThreadedTCPServer((HOST, PORT), ThreadedRequestHandler) "Server version: " + ServerVersion + "\n"\
"Protocol version: " + ProtocolVersion + "\n\n"\
if VERBOSITY >= 1: print("Starting server on", "To stop the server, press Ctrl-C\n")
server.server_address[0], "port", server.server_address[1], "...")
# Start a thread with the server -- that thread will then start one try:
# more thread for each request if VERBOSITY >= 1: print("Initializing server...")
ServerThread = threading.Thread(target = server.serve_forever) # Create server
server = ThreadedTCPServer((HOST, PORT), ThreadedRequestHandler)
# Exit the server thread when the main thread terminates
ServerThread.daemon = True if VERBOSITY >= 1: print("Starting server on",
ServerThread.start() server.server_address[0], "port", server.server_address[1], "...")
# Start a thread with the server -- that thread will then start one
while True: # more thread for each request
time.sleep(10) ServerThread = threading.Thread(target = server.serve_forever)
except KeyboardInterrupt: # Exit the server thread when the main thread terminates
print("\nGot Ctrl-C, shutting down server...") ServerThread.daemon = True
ServerThread.start()
try:
server.shutdown()
os.remove("pid") while True:
except: print("Failed to shutdown server correctly, "\ time.sleep(10)
"socket may be still in use or wasn't even started:",
sys.exc_info()) # exit if Ctrl-C is pressed
#except: except KeyboardInterrupt:
# print("\nAn error occured:\n", sys.exc_info(), "\n") print("\nGot Ctrl-C, shutting down server...")
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( """
description = "The server side of the "\
"aliased server remote control", import argparse
add_help = False)
parser = argparse.ArgumentParser(
description = "The server side of the "\
parser.add_argument( "aliased server remote control",
"--help", add_help = False)
action = "help",
help = "show this help message and exit")
parser.add_argument(
parser.add_argument( "--help",
"--version", action = "help",
action = "version", help = "show this help message and exit")
version = "Server version: " + program_version +\
" / Protocol version: " + protocol_version) parser.add_argument(
"--version",
grp_pid_file_failure = parser.add_mutually_exclusive_group() action = "version",
grp_pid_file_failure.add_argument( version = "Server version: " + program_version +\
"-n", " / Protocol version: " + protocol_version)
"--delete-pid-file",
action = "store_true", grp_pid_file_failure = parser.add_mutually_exclusive_group()
help = "deletes the pid file and starts the server") grp_pid_file_failure.add_argument(
"-n",
grp_pid_file_failure.add_argument( "--delete-pid-file",
"-m", action = "store_true",
"--allow-multiple-instances", help = "deletes the pid file and starts the server")
action = "store_true",
help = "ignores the pid file and starts the server. "\ grp_pid_file_failure.add_argument(
"Will not create another pid file.") "-m",
"--allow-multiple-instances",
parser.add_argument( action = "store_true",
"-v", help = "ignores the pid file and starts the server. "\
"--verbosity", "Will not create another pid file.")
type = int,
choices = range(0, 4), parser.add_argument(
# default = -1, "-v",
help = "increase output verbosity. Can be from 0 "\ "--verbosity",
"(only default output) to 3 (debug messages).") type = int,
choices = range(0, 4),
parser.add_argument( help = "increase output verbosity. Can be from 0 "\
"-h", "(only default output) to 3 (debug messages).")
"--host",
# default = -1, parser.add_argument(
help = "IP or hostname (use 0.0.0.0 for all interfaces) on which "\ "-h",
"the server should listen") "--host",
help = "IP or hostname (use 0.0.0.0 for all interfaces) on which "\
parser.add_argument( "the server should listen")
"-p",
"--port", parser.add_argument(
# default = -1, "-p",
help = "the port on which the server should listen") "--port",
help = "the port on which the server should listen")
parser.add_argument(
"-t", parser.add_argument(
"--timeout", "-t",
# default = -1, "--timeout",
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
class comm:
# handler the content aliases = dict()
def handler(client_address, data, aliases, server_version, protocol_version, verbosity): server_version = ""
ret = "" protocol_version = ""
verbosity = 0
# initializes global settings
def init(ServerVersion, ProtocolVersion, Verbosity, Aliases):
ret = ret +\ 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"
)