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
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?
\ No newline at end of file
Spawn log requires data from cloud and spawn tables. Disable only? Or duplicate data?
https://pythonhosted.org/netaddr/index.html
......@@ -87,6 +87,8 @@ def main(argv):
while True:
loopstarttime = datetime.now()
logger.info('Loop starts at ' + str(loopstarttime))
timingdb = open_timing_database()
filelist = check_configdir()
......@@ -100,11 +102,15 @@ def main(argv):
if (len(spawnlist) > 0):
spawn_process(spawnlist)
logger.info('Sleeping until next loop iteration')
# Sleep until the beginning of the next minute
sleeptime = 60 - datetime.utcnow().second
time.sleep(sleeptime)
def loadconfig():
logger.info('Loading spawner configuration')
config = ConfigParser.SafeConfigParser()
config.read(defaultconfigfile)
......
#!/usr/bin/python
#* 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 *#
#* it under the terms of the GNU General Public License as published by *#
......@@ -20,25 +20,34 @@
# Import libraries
import sys
import getopt
import re
import ConfigParser
import time
import logging
from datetime import datetime
import os, os.path
import re
# Global Variables
verbose = False
servername = 'SkyNet Server'
programname = 'SkyNet Server'
version = '1.0'
configfile = 'skynet.conf'
defaultconfigfile = 'skynet.default.conf'
cfg = {}
# Set up the logger
logging.basicConfig()
logger = logging.getLogger('spawner')
###
# Main
###
def main(argv):
try:
opts, args = getopt.gnu_getopt(argv, "hvVs:c:", \
["help", "verbose", \
"config", \
"version", \
"license"])
opts, args = getopt.gnu_getopt(argv,
"dhvVs:c:",
["debug", "help", "verbose", "config",
"version", "license"])
except getopt.GetoptError, err:
print str(err)
usage()
......@@ -46,14 +55,15 @@ def main(argv):
for o, a in opts:
if o in ("-v", "--verbose"):
global verbose
verbose = True
if o in ("-c", "--config"):
logger.setLevel(logging.INFO)
elif o in ("-d", "--debug"):
logger.setLevel(logging.DEBUG)
elif o in ("-c", "--config"):
global configfile
# TODO : This should be validated
configfile = o
elif o in ("-V", "--version"):
print '{0} {1}'.format(servername, version)
print '{0} {1}'.format(programname, version)
sys.exit()
elif o in ("-h", "--help"):
usage()
......@@ -64,124 +74,54 @@ def main(argv):
else:
assert False, "unhandled option"
# Check the service type
try:
service
except NameError:
print "Error: No Service defined"
usage()
sys.exit(2)
loadconfig()
# Check the filename option
try:
filehandle = open(statusfilename)
except IOError as err:
print str(err)
sys.exit(2)
# Main loop
while True:
loopstarttime = datetime.now()
if verbose:
print ("Parsing " + statusfilename + " for service " + service)
logger.info('Loop starts at ' + str(loopstarttime))
# Pass the file over to the parse function
parsestatus(filehandle, service)
# MAIN LOOP
# Close the file before we exit
filehandle.close()
logger.info('Sleeping until next loop iteration')
###
# ParseStatus
###
def parsestatus(filehandle, service):
definition = False
service_found = False
service_down = False
host_name = None
while 1:
line = filehandle.readline()
if not line:
break
# Handle each line here
line = line.strip();
# Compile regex first
def_comment = re.compile('^#')
def_start = re.compile('^(\w+) {$')
def_end = re.compile('^}$')
def_variable = re.compile('(\w+)=(.*)')
if (def_comment.match(line)):
continue
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
# Sleep until the beginning of the next minute
sleeptime = 60 - datetime.utcnow().second
time.sleep(sleeptime)
def loadconfig():
logger.info('Loading server configuration')
config = ConfigParser.SafeConfigParser()
config.read(defaultconfigfile)
try:
config.read(configfile)
except:
e = sys.exc_info()[0]
logger.exception('Unable to load config file = ' + e)
global cfg
cfg['configdir'] = config.get('skynet', 'configdir')
cfg['datadir'] = config.get('skynet', 'datadir')
logger.debug('configdir = {0}'.format(cfg['configdir']))
logger.debug('datadir = {0}'.format(cfg['datadir']))
###
# Usage
###
def usage():
print ('Usage: ' + sys.argv[0] + ' [OPTION]... ');
print ('Skynet')
print '{0}'.format(programname)
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 (' -f run in the foreground')
print (' -d, --debug debug')
print (' -h, --help display this help and exit')
print (' -v, --verbose verbose output')
print (' -V, --version output version information and exit')
......@@ -191,8 +131,9 @@ def usage():
# License
###
def license():
print('Copyright (C) 2013 Jason Frisvold <friz@godshell.com>');
print('License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl.html>.');
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('This is free software: you are free to change and redistribute it.');
print('There is NO WARRANTY, to the extent permitted by law.');
print('');
......@@ -204,4 +145,4 @@ try:
if __name__ == "__main__":
main(sys.argv[1:])
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