def main():
    pids = [proc for proc in os.listdir('/proc') if proc.isdigit()]

    # UIDs that have a listed process
    cleanup = set()
    # UIDs that have a non-listed process
    dont_cleanup = set()

    for proc in pids:
        try:
            status = open(os.path.join('/proc', proc, 'status'), 'r')
        except IOError:
            continue

        for line in status:
            elements = line.split(':')
            if elements[0] == 'Uid':
                uids = elements[1].split()
                real_uid = uids[0].strip()
            if elements[0] == 'Name':
                proc_name = elements[1].strip()

        if int(real_uid) > 1000:
            if proc_name in CHECK_FOR:
                cleanup.add(real_uid)

            if proc_name not in CHECK_FOR:
                dont_cleanup.add(real_uid)

    for uid in cleanup:
        if uid not in dont_cleanup:
            subprocess.call(['pkill', '-u', uid])
            syslog.openlog(ident='x2go_cleanup_processes', logoption=syslog.LOG_PID, facility=syslog.LOG_USER)
            syslog.syslog(syslog.LOG_NOTICE, 'Cleaning up processes for {0}'.format(uid))
            syslog.closelog()
Example #2
0
 def _log_syslog(self, prio):
     if self.__ident:
         syslog.openlog(ident=self.__ident, facility=self.__fac)
         syslog.syslog(prio, self.__last_message)
         syslog.closelog()
     else:
         syslog.syslog(prio | self.__fac, self.__last_message)
Example #3
0
def returner(ret):
    '''
    Return data to the local syslog
    '''

    _options = _get_options(ret)

    if not _verify_options(_options):
        return

    # Get values from syslog module
    level = getattr(syslog, _options['level'])
    facility = getattr(syslog, _options['facility'])

    # parse for syslog options
    logoption = 0
    for opt in _options['options']:
        logoption = logoption | getattr(syslog, opt)

    # Open syslog correctly based on options and tag
    if 'tag' in _options:
        syslog.openlog(ident=_options['tag'], logoption=logoption)
    else:
        syslog.openlog(logoption=logoption)

    # Send log of given level and facility
    syslog.syslog(facility | level, '{0}'.format(json.dumps(ret)))

    # Close up to reset syslog to defaults
    syslog.closelog()
Example #4
0
 def emit(self, record):
     hand = syslog.openlog(facility=self.facility)
     msg = self.format(record)
     syslog.syslog(
         self.priority_names.get(record.levelname.lower(), "debug"),
         msg)
     syslog.closelog()
Example #5
0
def debug(*args):
  msg = make_msg(args)
  if sys.stderr.isatty():
    logging.debug(msg)
  syslog.openlog(ident, syslog.LOG_NDELAY, facility)
  syslog.syslog(syslog.LOG_DEBUG, msg)
  syslog.closelog()
 def log(self, msg=''):
     if msg != '':
         sys.stdout.write(self.script_path + ': ' + str(msg) + '\n')
         syslog.openlog(ident='openvpn ' + self.name + ' ' + self.instance,
                        logoption=0, facility=syslog.LOG_DAEMON)
         syslog.syslog(syslog.LOG_INFO, msg)
         syslog.closelog()
Example #7
0
def send_10_log_messages_with_delay():
    syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_MAIL)
    for ind in range(10):
        msg = str(ind + 1) + '. Test Syslog Messages being sent.'
        syslog.syslog(syslog.LOG_EMERG, msg)
        time.sleep(1)
    syslog.closelog()
Example #8
0
def send_test_log_message():
    syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_KERN)
    for ind in range(5):
        msg = str(ind + 1) + '. Test Syslog Messages from different nodes.'
        syslog.syslog(syslog.LOG_EMERG, msg)
    time.sleep(1)
    syslog.closelog()
Example #9
0
def log(msg, level=syslog.LOG_NOTICE):
    if USE_STDERR:
        print >> sys.stderr, msg
    else:
        syslog.openlog( 'xs-activity-server', 0, syslog.LOG_USER )
        syslog.syslog(level, msg)
        syslog.closelog()
Example #10
0
def send_messages_of_all_facility_and_severity():
    dict_of_facility = {
        'LOG_KERN': 0,
        'LOG_USER': 1,
        'LOG_MAIL': 2,
        'LOG_DAEMON': 3,
        'LOG_AUTH': 4,
        'LOG_NEWS': 7,
        'LOG_UUCP': 8,
        'LOG_LOCAL0': 16,
        'LOG_CRON': 15,
        'LOG_SYSLOG': 5,
        'LOG_LOCAL1': 17}
    list_of_severity = ['LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
                        'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG']

    for each_facility in dict_of_facility:
        log_facility = dict_of_facility[each_facility]
        syslog.openlog(logoption=syslog.LOG_PID, facility=log_facility)
        for each_severity in list_of_severity:
            log_severity = list_of_severity.index(each_severity)
            msg = 'Test Message from ' + each_facility + \
                ' with severity ' + each_severity + '.'
            syslog.syslog(log_severity, msg)
        syslog.closelog()
        time.sleep(1)
Example #11
0
def main ():#funcion principal

	logs = open("FilesOutput/CompleteTables_Logs_error.txt", 'w')#se abre archivo log

	#abrimos syslog para registrar lo que realiza el script...
	syslog.openlog("CompleteTables.py", syslog.LOG_USER)

	syslog.syslog(syslog.LOG_INFO,"this script has created the next output files CompleteTables_Logs_error.txt")

	information_DB = ReadCSV(sys.argv[1])#obtenemos la informacion de la base de datos...

	syslog.syslog(syslog.LOG_INFO, "Completando datos en tablas no relacionadas")
	#se generan las conexiones
	data_connected_import = ConnectDB(information_DB['import'][0], information_DB['import'][1], information_DB['import'][2], information_DB['import'][3])
	data_connected_export = ConnectDB(information_DB['export'][0], information_DB['export'][1], information_DB['export'][2], information_DB['export'][3])

	#se realiza el mismo proceso para las diferentes tablas...
	#insertando elementos tabla tipodispositivo
	CompleteProcessInsertion(data_connected_export[1], data_connected_export[0], data_connected_import[1], data_connected_import[0], "tipo_dispositivo", "tipodispositivo", "tipo", "tipodispositivo_id_seq", 1)
	#insertando elementos tabla marca
	CompleteProcessInsertion(data_connected_export[1], data_connected_export[0], data_connected_import[1], data_connected_import[0], "marca", "marca", "marca", "marca_id_seq", 1)		
	#insertando elementos tabla tipousuario
	CompleteProcessInsertion(data_connected_export[1], data_connected_export[0], data_connected_import[1], data_connected_import[0], "tipo_usuario", "tipousuario", "tipo", "tipousuario_id_seq", 0)	
	#insertando elementos tabla estadodispositivo and tabla estadousuario
	CompleteProcessInsertion(data_connected_export[1], data_connected_export[0], data_connected_import[1], data_connected_import[0], "estado", "estadodispositivo", "descripcion", "estadodispositivo_id_seq", 1)	
	
	logs.write("ok")
	logs.close()

	syslog.closelog()#cerramos syslog
	return 0	
def main ():

	#abrimos syslog para registrar lo que realiza el script...
	syslog.openlog("VerificaRequisitos.py", syslog.LOG_USER)
	#abrimos archivo de texto con la informacion de la conexion...
	file_verificacion = open("FilesOutput/Verificacion.txt", 'w')#con w para crearlo

	#recibimos los argumentos
	data_import = sys.argv[2].split('_')
	data_export = sys.argv[1].split('_')

	syslog.syslog(syslog.LOG_INFO,"Verificando las conexiones a la base de datos")
	#hacemos la llamada a la funcion...
	Verificacion(data_export[0],data_export[1], data_export[2], data_export[3])#verificamos la conexion a la base de datos export
	Verificacion(data_import[0], data_import[1], data_import[2], data_import[3])#verificamos la conexion a la base de datos import

	#hacemos la verificacion de usuario root...
	usuario_root = VerificaUsuario()

	if (usuario_root == "ok"):
		file_verificacion.write("ok")#si todos los procesos terminan de ejecutarse de manera correcta simplemente se escribe un ok para el archivo
	else:
                file_verificacion.write("no")#hubo algun problema
			
	syslog.closelog()#cerramos syslog
def _log(priority, msg):
    syslog.openlog("slander", logoption=syslog.LOG_PID)
    syslog.syslog(priority, msg)
    syslog.closelog()

    if sys.stdout.isatty():
        print(msg)
Example #14
0
def warning(*args):
  msg = make_msg(args)
  if sys.stderr.isatty():
    logging.warning(msg)
  syslog.openlog(ident, syslog.LOG_NDELAY, facility)
  syslog.syslog(syslog.LOG_WARNING, msg)
  syslog.closelog()
def main ():

	#abrimos syslog para registrar lo que realiza el script...
	syslog.openlog("RemoveElementsConflictiv.py", syslog.LOG_USER)
	
	information_DB = ReadCSV(sys.argv[1])#obtenemos la informacion de la base de datos...
	# #make connections...
	data_connected_import = ConnectDB(information_DB['import'][0], information_DB['import'][1], information_DB['import'][2], information_DB['import'][3])
	data_connected_export = ConnectDB(information_DB['export'][0], information_DB['export'][1], information_DB['export'][2], information_DB['export'][3])
	print "Removiendo elementos conflictivos y elementos no existentes en csv"
	#obtengo la lista de macs...
	list_macs = ReadText("FilesOutput/GetMacslist_macs_not_exists.txt")
	list_macs_persistentes=RemoveMacsNotInCSV(data_connected_export[1], data_connected_export[0], list_macs)
	
	#eliminamos los datos que presentan problemas de union y que deben almacenar su informacion en un csv...
	list_equipos_conflictivos = GetListEquiposConflictivos(data_connected_export[1], data_connected_export[0])#obtenemos la lista de elementos conflictivos...
	info_equipos_conflictivos = RecolectaInformacionEquiposConflictivos(data_connected_export[1], list_equipos_conflictivos)
	GenerateCSV(info_equipos_conflictivos, data_connected_import[1])
	DeleteEquiposConflictivos(data_connected_export[1], data_connected_export[0], list_equipos_conflictivos)

	logs = open("FilesOutput/Remove.txt", 'w')
	logs.write("ok")
	logs.close()
	syslog.closelog()#cerramos syslog

	return 0
Example #16
0
def syslog(message, ident = "", priority = "info", facility = "syslog", options = []):
  """
  Send a string to syslog and return that same string.
  """
  priority = { "emerg":SYSLOG.LOG_EMERG, "alert":SYSLOG.LOG_ALERT, 
               "crit":SYSLOG.LOG_CRIT, "err":SYSLOG.LOG_ERR, 
               "warning":SYSLOG.LOG_WARNING, "notice":SYSLOG.LOG_NOTICE, 
               "info":SYSLOG.LOG_INFO, "debug":SYSLOG.LOG_DEBUG }.get(str(priority).lower(),0)
  facility = { "kern":SYSLOG.LOG_KERN, "user":SYSLOG.LOG_USER, 
               "mail":SYSLOG.LOG_MAIL, "daemon":SYSLOG.LOG_DAEMON, 
               "auth":SYSLOG.LOG_AUTH, "lpr":SYSLOG.LOG_LPR, 
               "news":SYSLOG.LOG_NEWS, "uucp":SYSLOG.LOG_UUCP, 
               "cron":SYSLOG.LOG_CRON, "syslog":SYSLOG.LOG_SYSLOG, 
               "local0":SYSLOG.LOG_LOCAL0, "local1":SYSLOG.LOG_LOCAL1, 
               "local2":SYSLOG.LOG_LOCAL2, "local3":SYSLOG.LOG_LOCAL3, 
               "local4":SYSLOG.LOG_LOCAL4, "local5":SYSLOG.LOG_LOCAL5, 
               "local6":SYSLOG.LOG_LOCAL6, "local7":SYSLOG.LOG_LOCAL7 }.get(str(facility).lower(),0)
  option = 0
  for opt in options:
    option += { "pid":SYSLOG.LOG_PID, "cons":SYSLOG.LOG_CONS, "ndelay":SYSLOG.LOG_NDELAY, 
                "nowait":SYSLOG.LOG_NOWAIT, "perror":SYSLOG.LOG_PERROR }.get(str(opt).lower(),0)
  message = str(message)
  ident = str(ident)
  if not ident: ident = os.path.basename(sys.argv[0])
  SYSLOG.openlog(ident = ident, logoption = option, facility = facility)
  add = ""
  for line in message.split("\n"):
    if line:
      SYSLOG.syslog(priority, add + line)
      add = " "
  SYSLOG.closelog()
  return message
Example #17
0
    def close(self):
        """
        Closes the handler.
        """

        syslog.closelog()
        logging.Handler.close(self)
Example #18
0
 def log(self, msg, priority=None):
     """
     Log an message string with a certain priority string. If that priority
     is greater than the pre-defined min priority log the message to 
     /var/log/messages.  The priority string must be one of EMERG, ALERT, 
     CRIT, ERR, WARNING, NOTICE, INFO, DEBUG
     
     args    : msg ...      message to be logged
               priority ... priority of the msg EMERG, ALERT, CRIT, ERR, 
                            WARNING, NOTICE, INFO or DEBUG
     excepts : 
     return  : none
     """
     # 'priority' is the actual level of the event, it must be one of ...
     # EMERG, ALERT, CRIT, ERR, WARNING, NOTICE, INFO, DEBUG
     # 'msg' will only be sent to syslog if 'priority' >= 'min_priority'
     
     # TODO: The Python syslog module is very broken - logging priorities are
     # ignored, this is a workaround ...
     if priority is None:
         priority = Logger.NOTICE
     msg = "{0}: [{1}] {2}".format(priority, self.module, msg)
     if self.case[priority] <= self.case[self.min_priority]: 
         syslog.openlog(self.program, syslog.LOG_PID) 
         syslog.syslog(msg)
         syslog.closelog()
Example #19
0
def log_error(msg, syslog_identifier, also_print_to_console=False):
    syslog.openlog(syslog_identifier)
    syslog.syslog(syslog.LOG_ERR, msg)
    syslog.closelog()

    if also_print_to_console:
        print msg
Example #20
0
def zlogFinal(success, config):
   global EBUFFER
   gconfig = config['global']
   if SYSLOG:
      syslog.closelog()
   if EMAIL:
      if success:
         ss = "SUCCESS"
      else:
         ss = "FAILURE"
      now = datetime.datetime.now()
      fromaddr = gconfig['email:from']
      toaddr = gconfig['email:to']
      smtpsrv = gconfig['email:smtpsrv']
      subject = "zbackup Report: %02d/%02d/%04d %02d:%02d (%s)" % (now.month, now.day, now.year, now.hour, now.minute, ss)
      body = ''.join(EBUFFER)
      msg = '\n'.join([
         "From: %s" % fromaddr,
         "To: %s" % toaddr,
         "Subject: %s" % subject,
         "",
         body])

      zloginfo("Sending email report to %s" % toaddr)
      s = smtplib.SMTP(smtpsrv)
      s.sendmail(fromaddr, [toaddr], msg)
      s.quit()

      EBUFFER = []
Example #21
0
def log(msg):
	"""
		Send a message to syslog
	"""
	syslog.openlog('OpenVPN', 0, syslog.LOG_DAEMON)
	syslog.syslog(syslog.LOG_INFO, msg)
	syslog.closelog()
Example #22
0
    def log_cef(self, message_name, message_description, type='LOG_INFO',
                items=[]):
        """
            log_cef method to actually write message to syslog
            param: message_name - Generic name of message type
            param: message_description - More verbose details of the message to
                be logged
            param: type - A string representation of the syslog facility,
              LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING,
              LOG_NOTICE, LOG_INFO, LOG_DEBUG
              http://unix.superglobalmegacorp.com/Net2/newsrc/sys/syslog.h.html
            param: items - List of cef specific key/value pairs

            typical usage:

        """
        # Open a connection to syslog to the proper facility

        syslog.openlog(self.prog_name, 0, self.facility)
        label_string = ''

        # Iterating over the items list and construct the label string to send
        for row in items:
            for key, value in row.items():
                label_string = "%s%s=%s " % (
                    label_string, str(key), str(value))
        cefmsg = 'CEF:0|Mozilla|%s|1.0|%s|%s|5|%s dhost=%s' %\
            (self.prog_name, message_name, message_description,
                label_string, os.uname()[1])
        try:
            syslog_level = getattr(syslog, type)
        except AttributeError:
            raise BaseException('Unable to find syslog type')
        syslog.syslog(syslog_level, cefmsg)
        syslog.closelog()
def log(txt, force=False):
    global log, log_enabled
    if not log_enabled and not force:
        return
    syslog.openlog("skolesys-backup")
    syslog.syslog(txt)
    syslog.closelog()
Example #24
0
def log_warning(msg, also_print_to_console=False):
    syslog.openlog(SYSLOG_IDENTIFIER)
    syslog.syslog(syslog.LOG_WARNING, msg)
    syslog.closelog()

    if also_print_to_console:
        click.echo(msg)
Example #25
0
def log_error(msg, also_print_to_console=False):
    syslog.openlog(SYSLOG_IDENTIFIER)
    syslog.syslog(syslog.LOG_ERR, msg)
    syslog.closelog()

    if also_print_to_console:
        click.echo(msg)
Example #26
0
def error(*args):
  msg = make_msg(args)
  if sys.stderr.isatty():
    logging.error(msg)
  syslog.openlog(ident, syslog.LOG_NDELAY, facility)
  syslog.syslog(syslog.LOG_ERR, msg)
  syslog.closelog()
Example #27
0
def main():
    parser = OptionParser()
    parser.add_option('-W', '--warning', action='store', dest='warning', default=100, type='int', help='The warning threshold we want to set')
    parser.add_option('-C', '--critical', action='store', dest='critical', default=200, type='int', help='The critical threshold we want to set')
    (options, args) = parser.parse_args()

    start = time.time()

    # syslog check start
    syslog.openlog( 'check_syslog' )
    syslog.syslog( syslog.LOG_DEBUG, 'Nagion syslog check' )
    syslog.closelog()
    # syslog check stop

    stop = time.time()
    result = int((stop - start) * 1000)
    if(result < options.warning):
        print "OK - %d ms" % result
        return 0
    if(result < options.critical):
        print "WARNING - %d ms" % result
        return 1
    else:
        print "CRITICAL - %d ms" % result
        return 2
Example #28
0
def exception():
  msg = traceback.format_exc()
  if sys.stderr.isatty():
    logging.error(msg)
  syslog.openlog(ident, syslog.LOG_NDELAY, facility)
  syslog.syslog(syslog.LOG_ERR, msg)
  syslog.closelog()
Example #29
0
def log_warning(msg, syslog_identifier, also_print_to_console=False):
    syslog.openlog(syslog_identifier)
    syslog.syslog(syslog.LOG_WARNING, msg)
    syslog.closelog()

    if also_print_to_console:
        print msg
Example #30
0
def log(statement, event=False):
    statement = str(statement)

    # Always print event related messages, even when --quiet is specified
    if options.quiet is True and event is False:
        return

    # Always log to syslog
    syslog.openlog("ha-nat")
    syslog.syslog(statement)
    syslog.closelog()

    # Always print to stdout
    print statement

    # Log to a file if one has been specified
    if options.logFile is not None:
        if not os.path.exists(os.path.dirname(options.logFile)):
            os.makedirs(os.path.dirname(options.logFile))

        logFile = open(options.logFile, 'a')
        ts = datetime.datetime.now()
        isFirst = True
        for line in statement.split("\n"):
            if isFirst:
                logFile.write("%s - %s\n" % (ts, line))
                isFirst = False
            else:
                logFile.write("%s -    %s\n" % (ts, line))
        logFile.close()
Example #31
0
def postClientDataToSysLog(client_obj):
    # Collection for Syslog and Splunk
    syslog.openlog(facility=syslog.LOG_DAEMON)
    dataStr = "client_id: {}, hostname: {}, ip: {}, mac_address: {}, fileVault_status: {}, os_ver: {}, loggedin_user: {}".format(
        client_obj.cuuid, client_obj.hostname, client_obj.ipaddr,
        client_obj.macaddr, client_obj.fileVaultStatus, client_obj.osver,
        client_obj.consoleuser)
    syslog.syslog(dataStr)
    syslog.closelog()
    log_Info("Wrote to syslog: " + dataStr)
    return
Example #32
0
def run_module():
    # define the available arguments/parameters that a user can pass to
    # the module
    module_args = dict(msg=dict(type='str', required=True),
                       priority=dict(type='str',
                                     required=False,
                                     choices=[
                                         "emerg", "alert", "crit", "err",
                                         "warning", "notice", "info", "debug"
                                     ],
                                     default='info'),
                       facility=dict(type='str',
                                     required=False,
                                     choices=[
                                         "kern", "user", "mail", "daemon",
                                         "auth", "lpr", "news", "uucp", "cron",
                                         "syslog", "local0", "local1",
                                         "local2", "local3", "local4",
                                         "local5", "local6", "local7"
                                     ],
                                     default='daemon'),
                       log_pid=dict(type='bool', required=False,
                                    default=False))

    module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)

    result = dict(changed=False,
                  priority=module.params['priority'],
                  facility=module.params['facility'],
                  log_pid=module.params['log_pid'],
                  msg=module.params['msg'])

    # basically, do nothing.
    if module.check_mode:
        return result

    # do the logging
    try:
        if module.params['log_pid']:
            syslog.openlog('ansible_syslogger',
                           logoption=syslog.LOG_PID,
                           facility=get_facility(module.params['facility']))
        else:
            syslog.openlog('ansible_syslogger',
                           facility=get_facility(module.params['facility']))
        syslog.syslog(get_priority(module.params['priority']),
                      module.params['msg'])
        syslog.closelog()
        result['changed'] = True

    except:
        module.fail_json(error='Failed to write to syslog', **result)

    module.exit_json(**result)
    def sysLog(self, debug=syslog.LOG_INFO, msg=None, doPrint=False):
        # log debug only if enabled
        if self.DEBUG == False and debug == syslog.LOG_DEBUG:
            return
        if doPrint and self.print_log_enabled:
            print("{}({}):{}".format(self.SYSLOG_IDENTIFIER, debug, msg))
        syslog.openlog(self.SYSLOG_IDENTIFIER)
        syslog.syslog(debug, msg)
        syslog.closelog()

        return
Example #34
0
def SendNotice(Message):

    try:

        syslog.openlog("genmon")
        syslog.syslog("%s" % Message)
        syslog.closelog()

    except Exception as e1:
        log.error("Error: " + str(e1))
        print("Error: " + str(e1))
Example #35
0
 def _syslog(self, facility, level, ident, message):
     _syslog.openlog(ident, facility)
     if isinstance(message, basestring):
         _syslog.syslog(_MLOG_TO_SYSLOG[level], message)
     else:
         try:
             for m in message:
                 _syslog.syslog(_MLOG_TO_SYSLOG[level], m)
         except TypeError:
             _syslog.syslog(_MLOG_TO_SYSLOG[level], str(message))
     _syslog.closelog()
Example #36
0
def send_messages_grater_than_1024_bytes():
    syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_MAIL)
    with open("message.txt", "r") as myfile:
        msg = myfile.readlines()[0]
        myfile.close()

    for ind in range(100):
        syslog.syslog(syslog.LOG_EMERG,
                      (msg[:5] + str(ind) + 'mymark' + msg[6:]))
        time.sleep(1)
    syslog.closelog()
Example #37
0
def _log(message, priority, verbose):
	tag = {
		syslog.LOG_INFO: "INFO",
		syslog.LOG_WARNING: "WARNING",
		syslog.LOG_ERR: "ERROR",
		syslog.LOG_DEBUG: "DEBUG"
	}
	if verbose:
		sys.stderr.write("{}: {}\n".format(tag[priority], message))
	syslog.openlog(facility=syslog.LOG_SYSLOG)
	syslog.syslog(priority, message)
	syslog.closelog()
def audit_log(msg):
    """Make an audit syslog, splitting up the request as required to prevent it
    being dropped or truncated"""

    lines = msg.split("\n")

    syslog.openlog("audit-log", syslog.LOG_PID, facility=syslog.LOG_AUTH)

    for line in lines:
        syslog.syslog(syslog.LOG_NOTICE, line.encode("utf-8"))

    syslog.closelog()
Example #39
0
def main():
    sc = cachedStatusObj('obs.sum.subaru.nao.ac.jp')
    syslog.openlog("SOSSstatusServer", syslog.LOG_PID,
                   syslog.LOG_WARNING | syslog.LOG_DAEMON)
    while True:
        line = sys.stdin.readline()
        if line == "":
            break
        aliasname = line.strip(' \r\n')
        val = sc.get_statusValue(aliasname)
        sys.stderr.write(str(val) + "\n")
    syslog.closelog()
Example #40
0
def auth_log(message, priority=syslog.LOG_INFO):
    """
    Sends errors to default authentication log

    @param string message
    @param integer priority
    @return void
    """

    syslog.openlog(facility=syslog.LOG_AUTH)
    syslog.syslog(priority, 'PAM RFID: ' + message)
    syslog.closelog()
Example #41
0
def logging(priority, message):
    """Logging.

    Arguments:
        priority: syslog priority
        message: log message
    """
    syslog.openlog(backup2swift.__name__, syslog.LOG_PID, syslog.LOG_LOCAL0)
    syslog.syslog(priority, str(message))
    syslog.closelog()
    print(message)
    exit(1)
Example #42
0
 def incoming(self, attackerIP, attackerPort, victimIP, victimPort,
              vulnName, timestamp, downloadMethod, loLogger, attackerID,
              shellcodeName):
     try:
         self.log_obj = amun_logging.amun_logging("log_syslog", loLogger)
         syslog_message = "Exploit: %s -> %s:%s %s (%s)" % (
             attackerIP, victimIP, victimPort, vulnName, downloadMethod)
         syslog.openlog('Amun', syslog.LOG_PID, syslog.LOG_LOCAL4)
         syslog.syslog(syslog.LOG_WARNING, syslog_message)
         syslog.closelog()
     except KeyboardInterrupt:
         raise
Example #43
0
def close():
    """Closes all handles. Invoke this before you exit your app
    """
    global logger, pid, process_name, inited, config, engine, conn, connected, levels, priorities, config_table, log_table, meta, log_fname, log_fhandle
    if conn: 
        conn.close()
    if engine: 
        engine.dispose()
    syslog.closelog()
    if (log_fhandle): 
        log_fhandle.close()
    inited = False
Example #44
0
    def exitError(self, msg):
        """
		Return to shell with an exit status 1 and the given message.
		"""
        sys.stderr.write(msg)
        syslog.openlog("ace")  # we don't have a logger yet ...
        syslog.syslog(
            syslog.LOG_ERR,
            "Can't start correlation engine (invalid configuration file): " +
            msg)
        syslog.closelog()
        sys.exit(1)
Example #45
0
def logging(priority, message):
    """

    Arguments:
        priority: syslog priority
        message: log message
    """
    syslog.openlog(NAME, syslog.LOG_PID, syslog.LOG_LOCAL0)
    syslog.syslog(priority, str(message))
    syslog.closelog()
    print(message)
    exit(1)
Example #46
0
def process(mysettings, key, logentries, fulltext):
	syslog.openlog("portage", syslog.LOG_ERR | syslog.LOG_WARNING | syslog.LOG_INFO | syslog.LOG_NOTICE, syslog.LOG_LOCAL5)
	for phase in EBUILD_PHASES:
		if not phase in logentries:
			continue
		for msgtype, msgcontent in logentries[phase]:
			if isinstance(msgcontent, str):
				msgcontent = [msgcontent]
			for line in msgcontent:
				line = "%s: %s: %s" % (key, phase, line)
				syslog.syslog(_pri[msgtype], line.rstrip("\n"))
	syslog.closelog()
Example #47
0
    async def do_update(self, data):
        """
        Update settings of SSH daemon service.

        If `bindiface` is empty it will listen for all available addresses.

        .. examples(websocket)::

          Make sshd listen only to igb0 interface.

            :::javascript
            {
                "id": "6841f242-840a-11e6-a437-00e04d680384",
                "msg": "method",
                "method": "ssh.update",
                "params": [{
                    "bindiface": ["igb0"]
                }]
            }

        """
        old = await self.config()

        new = old.copy()
        new.update(data)

        if new['bindiface']:
            verrors = ValidationErrors()
            iface_choices = await self.middleware.call('ssh.bindiface_choices')
            invalid_ifaces = list(filter(lambda x: x not in iface_choices, new['bindiface']))
            if invalid_ifaces:
                verrors.add(
                    'ssh_update.bindiface',
                    f'The following interfaces are not valid: {", ".join(invalid_ifaces)}',
                )
            verrors.check()

        await self._update_service(old, new)

        keyfile = "/usr/local/etc/ssh/ssh_host_ecdsa_key.pub"
        if os.path.exists(keyfile):
            with open(keyfile, "rb") as f:
                pubkey = f.read().strip().split(None, 3)[1]
            decoded_key = base64.b64decode(pubkey)
            key_digest = hashlib.sha256(decoded_key).digest()
            ssh_fingerprint = (b"SHA256:" + base64.b64encode(key_digest).replace(b"=", b"")).decode("utf-8")

            syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_USER)
            syslog.syslog(syslog.LOG_ERR, 'ECDSA Fingerprint of the SSH KEY: ' + ssh_fingerprint)
            syslog.closelog()

        return new
def restart_omi_if_crashed(omi_installed, mdsd):
    """
    Restart OMI if it crashed. Called from the main monitoring loop.
    :param omi_installed: bool indicating whether OMI was installed at the previous iteration.
    :param mdsd: Python Process object for the mdsd process, because it might need to be signaled.
    :return: bool indicating whether OMI was installed at this iteration (from this call)
    """
    omicli_path = "/opt/omi/bin/omicli"
    omicli_noop_query_cmd = omicli_path + " noop"
    omi_was_installed = omi_installed  # Remember the OMI install status from the last iteration
    omi_installed = os.path.isfile(omicli_path)

    if omi_was_installed and not omi_installed:
        hutil.log("OMI is uninstalled. This must have been intentional and externally done. "
                  "Will no longer check if OMI is up and running.")

    omi_reinstalled = not omi_was_installed and omi_installed
    if omi_reinstalled:
        hutil.log("OMI is reinstalled. Will resume checking if OMI is up and running.")

    should_restart_omi = False
    if omi_installed:
        cmd_exit_status, cmd_output = RunGetOutput(cmd=omicli_noop_query_cmd, should_log=False)
        should_restart_omi = cmd_exit_status is not 0
        if should_restart_omi:
            hutil.error("OMI noop query failed. Output: " + cmd_output + ". OMI crash suspected. "
                        "Restarting OMI and sending SIGHUP to mdsd after 5 seconds.")
            omi_restart_msg = RunGetOutput("/opt/omi/bin/service_control restart")[1]
            hutil.log("OMI restart result: " + omi_restart_msg)
            time.sleep(5)

    # mdsd needs to be signaled if OMI was restarted or reinstalled because mdsd used to give up connecting to OMI
    # if it fails first time, and never retried until signaled. mdsd was fixed to retry now, but it's still
    # limited (stops retrying beyond 30 minutes or so) and backoff-ed exponentially
    # so it's still better to signal anyway.
    should_signal_mdsd = should_restart_omi or omi_reinstalled
    if should_signal_mdsd:
        omi_up_and_running = RunGetOutput(omicli_noop_query_cmd)[0] is 0
        if omi_up_and_running:
            mdsd.send_signal(signal.SIGHUP)
            hutil.log("SIGHUP sent to mdsd")
        else:  # OMI restarted but not staying up...
            log_msg = "OMI restarted but not staying up. Will be restarted in the next iteration."
            hutil.error(log_msg)
            # Also log this issue on syslog as well
            syslog.openlog('diagnostic.py', syslog.LOG_PID,
                           syslog.LOG_DAEMON)  # syslog.openlog(ident, logoption, facility) -- not taking kw args in Python 2.6
            syslog.syslog(syslog.LOG_ALERT,
                          log_msg)  # syslog.syslog(priority, message) -- not taking kw args
            syslog.closelog()

    return omi_installed
Example #49
0
def main(args):
    syslog.openlog()
    #Get random message, PID, hostname and application name to concatenate them into the string_message
    random_message = get_generated_message_and_send_to_journal()
    process_id = os.getpid()
    hostname = socket.gethostname()
    name_of_application = get_application_name()
    journal_priority_no = get_journal_priority(random_message)
    journal_total_microsec = get_journal_microseconds(random_message)
    string_message = journal_priority_no + " " + str(
        hostname) + " " + name_of_application + "[" + str(
            process_id) + "]" + ": " + random_message
    variable_log = ""
    message_exists_in_syslog = 0
    microseconds_difference_acceptable = False
    time.sleep(2)
    #testlog = open_readonly(LOG_NAME)
    with open(LOG_NAME, "r") as testlog:
        for line in testlog:
            if string_message in line:
                message_exists_in_syslog += 1
                newline = line.split(" ")
                variable_log = newline[2]
                #the datetime is stripped according to the following format,in order to get hour,minute,seconds and convert them to microseconds.
                syslog_split_time = datetime.datetime.strptime(
                    variable_log, '%H:%M:%S.%f')
                syslog_hours = syslog_split_time.hour
                syslog_minutes = syslog_split_time.minute
                syslog_seconds = syslog_split_time.second
                syslog_microseconds = syslog_split_time.microsecond
                syslog_total_microseconds = 60 * 60 * 1000000 * syslog_hours + 60 * 1000000 * syslog_minutes + 1000000 * syslog_seconds + syslog_microseconds
                total_difference_in_microseconds = syslog_total_microseconds - journal_total_microsec
                print "Total difference in microseconds between journal timestamp and syslog timestamp is: " + str(
                    total_difference_in_microseconds)
                #see the documentation on robot test case, for why this amount of difference in microseconds is needed
                if total_difference_in_microseconds < 350:
                    print "times are almost identical, journal log has passed to syslog"
                    microseconds_difference_acceptable = True
                else:
                    print "times are different, some error occured during journal writing to syslog"
                    sys.exit(3)
    testlog.close()
    syslog.closelog()
    if message_exists_in_syslog == 1 and microseconds_difference_acceptable:
        print "string message was found in syslog"
        sys.exit(0)
    elif message_exists_in_syslog == 0:
        print "string_message was not found in any line of the syslog file"
        sys.exit(1)
    elif message_exists_in_syslog >= 2:
        print "duplicate entries of string message were found inside syslog"
        sys.exit(2)
Example #50
0
def main():

    try:
        signal.signal(signal.SIGINT, control_signal)
        signal.signal(signal.SIGTERM, control_signal)

        # Para comprobacion de excepciones ver sys.exc_info().
        # Comprobar si syslog esta operativo.
        if (subprocess.check_output(
                "ps -ea | grep -i syslogd | grep -v grep | wc -l",
                stderr=subprocess.STDOUT,
                shell=True)) != b'1\n':
            raise (SyslogNotRunning)

        if (len(sys.argv)) == 1:
            configValues = parseArgs("DEFAULT")
            logaction = syslog_entry(configValues["delay"],
                                     configValues["facility"],
                                     configValues["priority"], uuid.uuid4(),
                                     configValues["type"])
            logaction.printConfig()
            logaction.start()
        else:
            for argumentStr in sys.argv[1:(len(sys.argv))]:
                configValues = parseArgs(argumentStr)
                logaction = syslog_entry(configValues["delay"],
                                         configValues["facility"],
                                         configValues["priority"],
                                         uuid.uuid4(), configValues["type"])
                logaction.printConfig()
                logaction.start()

        while True:
            time.sleep(0.5)

    except ExitProgram:
        print("Finishing logging operations.......")
        for loggerThread in threading.enumerate():
            if loggerThread.getName() == "MainThread":
                continue
            loggerThread.close_flag.set()
            loggerThread.join()

    except SyslogNotRunning:
        print(
            "Syslog daemon is not running. Start syslog service before using syslog_generator."
        )
        sys.exit(2)

    print("Closing main program.")
    syslog.closelog()
    sys.exit(0)
Example #51
0
def cleanup(co):
    """Cleanup routine."""

    while co['pins']:
        pin_obj = co['pins'].pop()
        pin_obj.close()
    while co['signals']:
        s, h = co['signals'].pop()
        signal(s, h)
    if co['syslog']:
        syslog.closelog()
        co['syslog'] = False
    return
Example #52
0
 def _setfileobject(cls, fileobject, close=True):
     """Redirect log output to an opened file pointer."""
     cls._initlogger()
     if (cls._LOGFILE.fileno() != 1) and close:
         cls._LOGFILE.close()
     cls._LOGFILE = fileobject
     cls._logwrite = cls._logfile
     # clear other logging options:
     if cls._SYSLOG:
         cls._SYSLOG = None
         syslog.closelog()
     if cls._JOURNALLOG:
         cls._JOURNALLOG = False
Example #53
0
def log_cef(message_name, message_description, items=[]):
    FACILITY = syslog.LOG_LOCAL4
    syslog.openlog(PROG_NAME, 0, FACILITY)
    label_string = ''
    for row in items:
        for key, value in row.items():
            label_string = label_string.join("%s=%s " % (key, value))

    cefmsg = 'CEF:0|Mozilla|%s|1.0|%s|%s|5|%s dhost=%s' % (
        PROG_NAME, message_name, message_description, label_string,
        os.uname()[1])
    syslog.syslog(syslog.LOG_INFO, cefmsg)
    syslog.closelog()
Example #54
0
def _log(priority, msg, args, verbose=True):
    tag = {
        syslog.LOG_INFO: "INFO",
        syslog.LOG_WARNING: "WARNING",
        syslog.LOG_ERR: "ERROR",
        syslog.LOG_DEBUG: "DEBUG",
    }
    msg = msg % args if args else msg
    if verbose:
        sys.stderr.write("{}: {}\n".format(tag[priority], msg))
    syslog.openlog(facility=syslog.LOG_SYSLOG)
    syslog.syslog(priority, msg)
    syslog.closelog()
Example #55
0
        def producerlog(self, repo, action, *args):
            """Write to the producer syslog facility."""
            ident = self.config('replicationproducer', 'syslogident', 'vcsreplicator')
            facility = self.config('replicationproducer', 'syslogfacility', 'LOG_LOCAL2')
            facility = getattr(syslog, facility)
            syslog.openlog(ident, 0, facility)

            if not isinstance(repo, str):
                repo = repo.replicationwireprotopath

            pre = '%s %s %s' % (os.environ.get('USER', '<unknown>'), repo, action)
            syslog.syslog(syslog.LOG_NOTICE, '%s %s' % (pre, ' '.join(args)))
            syslog.closelog()
Example #56
0
def log_cef(message_name, message_description, items=None):
    facility = syslog.LOG_LOCAL4
    syslog.openlog(PROG_NAME, 0, facility)
    label_string = ''
    if items is not None:
        for row in items:
            for key, value in list(row.items()):
                label_string = label_string.join("%s=%s " % (key, value))
    cefmsg = 'CEF:0|Mozilla|%s|1.0|%s|%s|5|%s dhost=%s' % (
        PROG_NAME, message_name, message_description, label_string,
        os.uname()[1])  # noqa
    syslog.syslog(syslog.LOG_INFO, cefmsg)
    syslog.closelog()
Example #57
0
    def write_error(self, text, *args):
        """
        Writes an error to the log.

        Args:
            text (str): Text to write to the log.
            args (tuple) : Arguments to use when formatting the text.

        """
        if not self._error_level_enabled: return
        message = text.format(*args)
        openlog(ident=self.__ident, facility=self.__facility)
        syslog(LOG_ERR, message)
        closelog()
Example #58
0
 def _process_message(self):
     try:
         msg = self._deque.popleft()
         tag = msg['tag']
         facility = msg['facility']
         severity = msg['severity']
         syslog.openlog(tag, 0, getattr(syslog, facility))
         syslog.syslog(getattr(syslog, severity),
                       self._shrink(msg['payload']))
         syslog.closelog()
         return True
     except IndexError:
         time.sleep(0.1)
         return False
Example #59
0
def main():
    # define the available arguments/parameters that a user can pass to
    # the module
    module_args = dict(ident=dict(type='str', default='ansible_syslogger'),
                       msg=dict(type='str', required=True),
                       priority=dict(type='str',
                                     required=False,
                                     choices=[
                                         "emerg", "alert", "crit", "err",
                                         "warning", "notice", "info", "debug"
                                     ],
                                     default='info'),
                       facility=dict(type='str',
                                     required=False,
                                     choices=[
                                         "kern", "user", "mail", "daemon",
                                         "auth", "lpr", "news", "uucp", "cron",
                                         "syslog", "local0", "local1",
                                         "local2", "local3", "local4",
                                         "local5", "local6", "local7"
                                     ],
                                     default='daemon'),
                       log_pid=dict(type='bool', required=False,
                                    default=False))

    module = AnsibleModule(argument_spec=module_args, )

    result = dict(changed=False,
                  ident=module.params['ident'],
                  priority=module.params['priority'],
                  facility=module.params['facility'],
                  log_pid=module.params['log_pid'],
                  msg=module.params['msg'])

    # do the logging
    try:
        syslog.openlog(module.params['ident'],
                       syslog.LOG_PID if module.params['log_pid'] else 0,
                       get_facility(module.params['facility']))
        syslog.syslog(get_priority(module.params['priority']),
                      module.params['msg'])
        syslog.closelog()
        result['changed'] = True

    except Exception as exc:
        module.fail_json(error='Failed to write to syslog %s' % to_native(exc),
                         exception=traceback.format_exc(),
                         **result)

    module.exit_json(**result)
Example #60
0
def auth_log(host, user, passwd):
    """Send errors to default auth log"""
    today = datetime.date.today()
    time = datetime.datetime.today()
    f = open('/var/log/telnet-' + str(today) + '.csv', 'ab')
    csvwriter = csv.writer(f)
    syslog.openlog(facility=syslog.LOG_AUTH)
    syslog.syslog("Telnet Attack Logged:(" + str(host) + ":" + str(user) +
                  ":" + str(passwd) + ")")
    syslog.closelog()
    attempt = [host, user, passwd, time]
    if (host != 'localhost'):
        csvwriter.writerow(attempt)
    f.close()