Commit 405d2165 authored by Jason Frisvold's avatar Jason Frisvold
Browse files

- Add additional logging to spawner

- Basic framework for server
- Some note additions
parent 8686a7bc
...@@ -31,4 +31,6 @@ https://bitbucket.org/vinay.sajip/python-gnupg ...@@ -31,4 +31,6 @@ https://bitbucket.org/vinay.sajip/python-gnupg
Slim framework for the web interface? https://github.com/codeguy/Slim Slim framework for the web interface? https://github.com/codeguy/Slim
Spawn log requires data from cloud and spawn tables. Disable only? Or duplicate data? Spawn log requires data from cloud and spawn tables. Disable only? Or duplicate data?
\ No newline at end of file
https://pythonhosted.org/netaddr/index.html
...@@ -87,6 +87,8 @@ def main(argv): ...@@ -87,6 +87,8 @@ def main(argv):
while True: while True:
loopstarttime = datetime.now() loopstarttime = datetime.now()
logger.info('Loop starts at ' + str(loopstarttime))
timingdb = open_timing_database() timingdb = open_timing_database()
filelist = check_configdir() filelist = check_configdir()
...@@ -100,11 +102,15 @@ def main(argv): ...@@ -100,11 +102,15 @@ def main(argv):
if (len(spawnlist) > 0): if (len(spawnlist) > 0):
spawn_process(spawnlist) spawn_process(spawnlist)
logger.info('Sleeping until next loop iteration')
# Sleep until the beginning of the next minute # Sleep until the beginning of the next minute
sleeptime = 60 - datetime.utcnow().second sleeptime = 60 - datetime.utcnow().second
time.sleep(sleeptime) time.sleep(sleeptime)
def loadconfig(): def loadconfig():
logger.info('Loading spawner configuration')
config = ConfigParser.SafeConfigParser() config = ConfigParser.SafeConfigParser()
config.read(defaultconfigfile) config.read(defaultconfigfile)
......
#!/usr/bin/python #!/usr/bin/python
#* Skynet - Automated "Cloud" Security Scanner *# #* Skynet - Automated "Cloud" Security Scanner *#
#* Copyright (C) 2013 Jason Frisvold <friz@godshell.com> *# #* Copyright (C) 2014 Jason Frisvold <friz@godshell.com> *#
#* *# #* *#
#* This program is free software; you can redistribute it and/or modify *# #* 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 *# #* it under the terms of the GNU General Public License as published by *#
...@@ -20,25 +20,34 @@ ...@@ -20,25 +20,34 @@
# Import libraries # Import libraries
import sys import sys
import getopt import getopt
import re import ConfigParser
import time
import logging import logging
from datetime import datetime from datetime import datetime
import os, os.path
import re
# Global Variables # Global Variables
verbose = False verbose = False
servername = 'SkyNet Server' programname = 'SkyNet Server'
version = '1.0' version = '1.0'
configfile = 'skynet.conf'
defaultconfigfile = 'skynet.default.conf'
cfg = {}
# Set up the logger
logging.basicConfig()
logger = logging.getLogger('spawner')
### ###
# Main # Main
### ###
def main(argv): def main(argv):
try: try:
opts, args = getopt.gnu_getopt(argv, "hvVs:c:", \ opts, args = getopt.gnu_getopt(argv,
["help", "verbose", \ "dhvVs:c:",
"config", \ ["debug", "help", "verbose", "config",
"version", \ "version", "license"])
"license"])
except getopt.GetoptError, err: except getopt.GetoptError, err:
print str(err) print str(err)
usage() usage()
...@@ -46,14 +55,15 @@ def main(argv): ...@@ -46,14 +55,15 @@ def main(argv):
for o, a in opts: for o, a in opts:
if o in ("-v", "--verbose"): if o in ("-v", "--verbose"):
global verbose logger.setLevel(logging.INFO)
verbose = True elif o in ("-d", "--debug"):
if o in ("-c", "--config"): logger.setLevel(logging.DEBUG)
elif o in ("-c", "--config"):
global configfile global configfile
# TODO : This should be validated # TODO : This should be validated
configfile = o configfile = o
elif o in ("-V", "--version"): elif o in ("-V", "--version"):
print '{0} {1}'.format(servername, version) print '{0} {1}'.format(programname, version)
sys.exit() sys.exit()
elif o in ("-h", "--help"): elif o in ("-h", "--help"):
usage() usage()
...@@ -64,124 +74,54 @@ def main(argv): ...@@ -64,124 +74,54 @@ def main(argv):
else: else:
assert False, "unhandled option" assert False, "unhandled option"
# Check the service type loadconfig()
try:
service
except NameError:
print "Error: No Service defined"
usage()
sys.exit(2)
# Check the filename option # Main loop
try: while True:
filehandle = open(statusfilename) loopstarttime = datetime.now()
except IOError as err:
print str(err)
sys.exit(2)
if verbose: logger.info('Loop starts at ' + str(loopstarttime))
print ("Parsing " + statusfilename + " for service " + service)
# Pass the file over to the parse function # MAIN LOOP
parsestatus(filehandle, service)
# Close the file before we exit logger.info('Sleeping until next loop iteration')
filehandle.close()
### # Sleep until the beginning of the next minute
# ParseStatus sleeptime = 60 - datetime.utcnow().second
### time.sleep(sleeptime)
def parsestatus(filehandle, service):
definition = False def loadconfig():
service_found = False logger.info('Loading server configuration')
service_down = False
host_name = None config = ConfigParser.SafeConfigParser()
while 1: config.read(defaultconfigfile)
line = filehandle.readline()
if not line: try:
break config.read(configfile)
# Handle each line here except:
line = line.strip(); e = sys.exc_info()[0]
logger.exception('Unable to load config file = ' + e)
# Compile regex first
def_comment = re.compile('^#') global cfg
def_start = re.compile('^(\w+) {$')
def_end = re.compile('^}$') cfg['configdir'] = config.get('skynet', 'configdir')
def_variable = re.compile('(\w+)=(.*)') cfg['datadir'] = config.get('skynet', 'datadir')
if (def_comment.match(line)): logger.debug('configdir = {0}'.format(cfg['configdir']))
continue logger.debug('datadir = {0}'.format(cfg['datadir']))
elif (def_end.match(line)):
# Handle any downs
if service_found and service_down and host_name:
curtime = datetime.today()
command = str("[{0}] PROCESS_SERVICE_CHECK_RESULT;{1};{2};0;OK".format(curtime.strftime('%s'), host_name, service))
try:
cmdfile = open(cmdfilename, 'a')
except IOError as err:
print str(err)
sys.exit(2)
cmdfile.write(command)
print "Marking {0} - {1} as up.".format(host_name, service)
cmdfile.close()
if verbose:
print command
# Reset the variables
definition = False
service_found = False
service_down = False
host_name = None
if verbose:
print 'Definition End'
m = def_start.match(line)
if not m is None:
definition = True
if verbose:
print 'Definition Start'
m = def_variable.match(line)
if not m is None:
# Capture the variable input
var = m.groups()[0]
val = m.groups()[1]
if verbose:
print "Variable ({0}) = Value ({1})".format(var, val)
# Check for the variables we care about
if (var == 'service_description'):
if (val == service):
service_found = True
if verbose:
print 'Service found'
if (var == 'host_name'):
host_name = val
if verbose:
print 'Host found - {0}'.format(host_name)
if (var == 'current_state'):
if (val == '1' or val == '2'):
service_down = True
if verbose:
print 'Service Down'
#print line
### ###
# Usage # Usage
### ###
def usage(): def usage():
print ('Usage: ' + sys.argv[0] + ' [OPTION]... '); print ('Usage: ' + sys.argv[0] + ' [OPTION]... ');
print ('Skynet') print '{0}'.format(programname)
print print
print ('Mandatory arguments to long options are mandatory for short options too.') print ('Mandatory arguments to long options are mandatory for short ' \
'options too.')
print (' -c <file> configuration file') print (' -c <file> configuration file')
print (' -f run in the foreground') print (' -d, --debug debug')
print (' -h, --help display this help and exit') print (' -h, --help display this help and exit')
print (' -v, --verbose verbose output') print (' -v, --verbose verbose output')
print (' -V, --version output version information and exit') print (' -V, --version output version information and exit')
...@@ -191,8 +131,9 @@ def usage(): ...@@ -191,8 +131,9 @@ def usage():
# License # License
### ###
def license(): def license():
print('Copyright (C) 2013 Jason Frisvold <friz@godshell.com>'); print('Copyright (C) 2014 Jason Frisvold <friz@godshell.com>');
print('License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl.html>.'); print('License GPLv2+: GNU GPL version 2 or later ' \
'<http://gnu.org/licenses/gpl.html>.');
print('This is free software: you are free to change and redistribute it.'); print('This is free software: you are free to change and redistribute it.');
print('There is NO WARRANTY, to the extent permitted by law.'); print('There is NO WARRANTY, to the extent permitted by law.');
print(''); print('');
...@@ -204,4 +145,4 @@ try: ...@@ -204,4 +145,4 @@ try:
if __name__ == "__main__": if __name__ == "__main__":
main(sys.argv[1:]) main(sys.argv[1:])
except KeyboardInterrupt: except KeyboardInterrupt:
sys.exit() sys.exit()
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment