def start(self):
        """ All program flow is handled here """

        # usage, init, checks
        Usage.banner()
        args = ArgsParser.parseArgs()
        self.opts = vars(args)
        Check.checkArgc()
        Check.checkArgs(['-n', '-m'])
        Check.checkActions(self.opts['action'])
        Check.checkReportFormat(self.opts['format'])

        # ini config
        Wrapper.msg("Reading configuration file " + "'" + self.opts['config'] +
                    "'")
        self.ini = IniConfig(self.opts['config'])
        self.ini.readConfig()
        Check.checkIniFile(self.ini.config)

        # additional options from config file
        self.getOptions()

        ### nessus actions ###

        # nessus report
        if self.opts['action'] in ACTIONS:
            self.processReports(self.opts['action'])

        # send reports
        if self.opts['mail']:
            if self.opts['action'] in ACTIONS:
                self.sendReports(self.opts['action'])

        return
Пример #2
0
    def handle(self):
        """
        Handle a chat message.

        This could be either a public message or a private message.
        """
        Check.message(self)
Пример #3
0
 def song_update(self):
     s_id = input("enter song's id: ")
     if Check.check_song(s_id):
         name = input("enter song's name: ")
         language = input("enter song's language: ")
         album_id = input("enter id of album in which song is: ")
         while not Check.check_album(album_id):
             string = input(
                 "There is no such album\nYou can add it\n(y/n): ")
             for case in Switch(string):
                 if case('y'):
                     album = self.album_input()
                     album_id = album.id
                     db.insert_album(album)
                     break
                 if case('n'):
                     print("can't insert song")
                     return
                 else:
                     print("wrong input, try again!")
         song = Song(s_id, name, language, album_id)
         return song
     else:
         print("No such song in db")
         return None
Пример #4
0
 def add_note(self):
     note_name = Check(
         input(
             'Введите через пробел имя, фамилию, номер телефона(без плюса), город и e-mail:'
         ))
     if note_name.note_is_right():
         handbook = open(self.name + '.txt', 'r')
         notes = handbook.read()
         handbook.close()
         if note_name.check_to_str() in notes:
             print('Такая запись уже существует.', end='\n')
             return
         if note_name.phone_number in notes:
             print('Запись с таким номером уже существует.', end='\n')
             return
         if note_name.name and note_name.last_name in notes:
             print('Запись c такими именем и фамилией уже существует.',
                   end='\n')
             return
         if note_name.email in notes:
             print('Запись с таким e-mail уже существует.', end='\n')
             return
         handbook = open(self.name + '.txt', 'a')
         handbook.write(note_name.check_to_str() + '\n')
         handbook.close()
         print('Запись добавлена.', end='\n')
     else:
         print('Неверный ввод. Повторите попытку.', end='\n')
Пример #5
0
 def album_update(self):
     a_id = input("enter album's id: ")
     if Check.check_album(a_id):
         name = input("enter album's name: ")
         presentation_date = self.get_date()
         songs_number = input("enter number of songs in album: ")
         band_id = input("enter id of band which created album: ")
         while not Check.check_band(band_id):
             string = input(
                 "There is no such band\nYou can add it\n(y/n): ")
             for case in Switch(string):
                 if case('y'):
                     band = self.band_input()
                     band_id = band.id
                     db.insert_band(band)
                     break
                 if case('n'):
                     print("can't insert album")
                     return
                 else:
                     print("wrong input, try again!")
         album = Album(a_id, name, presentation_date, songs_number, band_id)
         return album
     else:
         print("No such album in db")
         return None
Пример #6
0
def test_check():
    check = Check()
    check.letter_guessed = "a"
    word = "frog"
    spaces = ["_", "_", "_", "_"]
    check.check(word, spaces)
    assert check.incorrect_guesses == 1
    def start(self):
        """ All program flow is handled here """

        # usage, init, checks
        Usage.banner()
        args = ArgsParser.parseArgs()
        self.opts = vars(args)
        Check.checkArgc()
        Check.checkArgs(['-n', '-m'])
        Check.checkActions(self.opts['action'])
        Check.checkReportFormat(self.opts['format'])

        # ini config
        Wrapper.msg("Reading configuration file " + "'" +
                self.opts['config'] + "'")
        self.ini = IniConfig(self.opts['config'])
        self.ini.readConfig()
        Check.checkIniFile(self.ini.config)

        # additional options from config file
        self.getOptions()

        ### nessus actions ###

        # nessus report
        if self.opts['action'] in ACTIONS:
            self.processReports(self.opts['action'])

        # send reports
        if self.opts['mail']:
            if self.opts['action'] in ACTIONS:
                self.sendReports(self.opts['action'])

        return
Пример #8
0
 def cond_weight():
     weight = None
     cond = Check.check_yn("est-ce un produit conditionné (o/n)? ")
     if cond == 'o':
         weight = Check.check_weight_price("entrez le poids conditionné : ",
                                           weight=True)
     return weight
Пример #9
0
 def purchase_get_data():
     store_id = 0
     with open("card_list_code.json", 'r') as card:
         list_card_code = json.load(card)
     today = datetime.today()
     date_choice = Check.check_yn(
         "voulez_vous garder la date et l'heure du jour (o/n)? ")
     if date_choice == 'o':
         date = datetime.today().date()
         hour = datetime.today().time().isoformat(timespec='seconds')
     else:
         date = Check.check_date("enrez la date (jj/mm/YYYY): ")
         hour = Check.check_hour("entrez l'heure (H:M): ")
     while store_id == 0 or store_id == 'q':
         store_id = Store.get_store("entrez le nom du magasin: ")
     while True:
         card_code = Check.check_cardcode(
             "entrez le numéro de carte de paiement ( les 4 dernier chiffres de la carte ): "
         )
         if not Purchase.card_code_isfind(list_card_code, card_code):
             new_card = Check.check_yn("nouvelle carte (o/n)? ")
             if new_card == 'o':
                 Purchase.change_code(card_code, list_card_code)
                 break
         else:
             break
     return date, hour, card_code, today, store_id
Пример #10
0
    def test_check_no_http_status_code(self):
        '''If there is no status code it should raise an exception'''
        http_response = Mock(status=None)
        errors = []
        endpoint = {'response': {'codes': [100, 101, 200]}}

        Check.check_status_codes(http_response, endpoint, errors)
        self.assertRaises(Exception)
Пример #11
0
 def permier_level(level):
     print("\n----1 - Level 1")
     print("----4 - Sortir")
     level = Check.checkInt("Que voulez-vous faire : ")
     while level != 1 and level != 4:
         level = Check.checkInt(
             "Réponse incorect, veuillez saisir le choix 1 ou 4 ! ")
     return level
Пример #12
0
 def test_ValueError_raised_after_clear_check_with_not_deposited(self):
     """ test if the ValueError raised after clear_check with the check 
     which not in the pending check. """
     bank_account = set_up()
     ck1 = Check(7890)
     fake_check = Check(1234)
     bank_account.deposit(ck1)
     with self.assertRaises(ValueError):
         bank_account.clear_check(fake_check)
Пример #13
0
 def fonction_mise(argent, level):
     if level == 1:
         mise = Check.checkInt("\nLe jeu commence, entrez votre mise : ")
     else:
         mise = Check.checkInt("\nEntrez votre mise : ")
     while mise < 1 or mise > argent:
         print("Erreur, votre mise est plus elevé que votre solde.")
         mise = Check.checkInt("Entrer SVP un montant entre 1 et " + str(argent) + " € : ")
     return mise
Пример #14
0
    def test_check_endpoints_timeout(self):

        endpoint = {'notificationEndpoint': {'url': ''}, 'checks': [{'request': {'endpoint': 'http://127.0.0.1:1',  'method': 'GET', 'connectTimeout': 0.001}, 'response': {'codes': [200]}, 'service': 'Gitlab'}]}

        my_check = Check(endpoint)
        my_check.check_endpoints()

        result = len(my_check.errors_list)
        self.assertEqual(result, 1)
Пример #15
0
 def __init__(self):
     self.Tablero = Tablero()
     self.turnoactual = "W"
     self.Check = Check(self)
     self.Enroque = Enroque(self)
     self.texto = {"W": "Las blancas!", "B": "Las negras!"}
     self.victoria = False
     self.turno = False
     self.enroque = None
     self.oficial = None
Пример #16
0
 def __init__(self):
     """The class constructor.
     
     Args:
         self (Director): an instance of Director.
     """
     self.puzzle = Puzzle()
     self.jumper = Jumper()
     self.check = Check()
     self.keep_playing = True
Пример #17
0
    def test_check_status_codes_list_empty(self):
        '''No errors should be added to the errors list if the codes list is empty'''
        http_response = Mock(status_code=200)
        errors = []
        endpoint = {'response': {'codes': []}}

        Check.check_status_codes(http_response, endpoint, errors)

        result = len(errors)
        self.assertEqual(result, 0)
Пример #18
0
    def test_check_status_no_codes_list(self):
        '''No errors should be added to the errors list if code list doesnt exist'''
        http_response = Mock(status_code=200)
        errors = []
        endpoint = {'response': {}}

        Check.check_status_codes(http_response, endpoint, errors)

        result = len(errors)
        self.assertEqual(result, 0)
Пример #19
0
    def test_check_body_text_not_found(self):
        '''An error should be added to the errors list if the body is found in the response text'''
        http_response = Mock(text="my text \n foo\nbarFooo")
        errors = []
        endpoint = {'response': {'body': "NOTFOUND"}}

        Check.check_status_codes(http_response, endpoint, errors)

        result = len(errors)
        self.assertEqual(result, 0)
Пример #20
0
    def test_check_body_no_body(self):
        '''No error should be added to the errors list if the body attribute doesnt exist'''
        http_response = Mock(text="my text \n foo\nbarFooo")
        errors = []
        endpoint = {'response': {}}

        Check.check_status_codes(http_response, endpoint, errors)

        result = len(errors)
        self.assertEqual(result, 0)
Пример #21
0
    def test_check_status_codes_found(self):
        '''No errors should be added to the errors list if the status code is not found in the codes list'''
        http_response = Mock(status_code=200)
        errors = []
        endpoint = {'response': {'codes': [100, 101, 200]}}

        Check.check_status_codes(http_response, endpoint, errors)

        result = len(errors)
        self.assertEqual(result, 0)
Пример #22
0
 def schedule_check(self, cycle=TESTER_CYCLE):
     '''
     定时测试代理
     :param cycle:
     :return:
     '''
     check = Check()
     while True:
         print('测试器开始运行')
         check.run()
         time.sleep(cycle)
Пример #23
0
 def __init__(self):
     with open(file='./conf/actorConf.json', mode='r',
               encoding='utf-8') as f:
         content = f.read()
         content_json = json.loads(content)
         self.Head = content_json['Head']
         self.End = content_json['End']
     # 用户检查校验更正文本的输入与输出
     self.myCheck = Check()
     self.parser = TextParser()
     self.classifier = Classifier()
     self.ruleParser = RuleParser()
Пример #24
0
 def purch_pro_get_datas(product_name, food=False):
     product_id = weight = None
     print("product et weight dans purchpro get datas: ", (product_id, weight))
     print("le food dans purchet pro de purchase_product: ", food)
     product_id, weight, food = Product.product_get_datas(product_name)
     if weight == None and food:
         weight = Check.check_weight_price("entrez le poids du produit: ", weight=True)
     if product_id:
         price = Check.check_weight_price("entrez le prix de l'article: ", price=True)
     else:
         price = None
     return product_id, price, weight
Пример #25
0
 def passage_level_superieur(level):
     level += 1
     print("\nSuper ! Vous passez au Level " + str(level))
     print("\n----" + str(level) + " - Pour passer au level " + str(level))
     print("----4 - Sortir")
     levelprecedent = level
     level = Check.checkInt("Que voulez-vous faire : ")
     while levelprecedent != level and level != 4:
         level = Check.checkInt(
             "Réponse incorect, veuillez saisir le choix " +
             str(levelprecedent) + " ou 4 ! ")
     return level
Пример #26
0
def index():
    if request.method == 'POST':
        msg = request.get_json()
        chat_id, txt = prase_message(msg)
        try:
            checking = Check(txt)
            if checking.msg_for_bot():
                bot.send_message(checking.msg_for_bot(), chat_id)
        except Exception as value:
            bot.send_message(str(value), chat_id)
        return Response('OK', status=200)
    else:
        return '<h1>Ngon</h1>'
Пример #27
0
 def login(self):
     print("*------------------------------------*")
     print("|                                    |")
     print("|           管理员登陆界面           |")
     print("|                                    |")
     print("*------------------------------------*")
     check = Check()
     check.userName(self.admin, self.password)
     print("*-------------登陆成功---------------*")
     print("   正在跳转到系统功能界面,请稍候...  ")
     del check
     time.sleep(3)
     return
Пример #28
0
    def login(self):
        print("--------------------------------------")
        print("                                      ")
        print("            Admin login.....          ")
        print("                                      ")
        print("--------------------------------------")

        check = Check()
        check.userName(self.admin, self.pwd)

        print("--------------Login success-----------")
        print("          Please wait a moment...     ")
        del check
        time.sleep(1)
        return
Пример #29
0
 def getCheckedOutItems(self):
     self.connect()
     try:
         c = self.connection.cursor()
         c.execute('select * from POSHEA1."CHECK"')
         a = []
         for row in c:
             temp = Check('', '', '')
             temp.adapt(row)
             a.append(temp.dictify())
         self.disconnect()
         return json.dumps(a)
     except:
         self.disconnect()
         return json.dumps([])
Пример #30
0
 def __init__(self, name, config, url = "", frequency = 1, timeout = 30, 
             username = None, password = None, match_string = None,
             match_not_string = None, use_regexp = False,
             response_time = 60, valid_http_codes = "200,301,304"):
     Check.__init__(self, name, config)
     self.url = config['url']
     self.name = name
     self.frequency = frequency
     self.timeout = timeout
     self.username = username
     self.password = password
     self.match_string = match_string
     self.match_not_string = match_not_string
     self.use_regexp = use_regexp
     self.response_time = response_time
     self.valid_http_codes = valid_http_codes
Пример #31
0
 def false_purchase():
     want_to_continue = True
     while want_to_continue:
         with Connection.get_cursor() as cur:
             cur.execute("""SELECT * FROM purchase WHERE purch = False;""")
             purchase_incourse_list = cur.fetchall()
         if not purchase_incourse_list:
             print(
                 "la liste est vide: pas de ticket en cours d'enregistrement"
             )
             want_to_continue = False
         else:
             user_choice = Display.display_values(
                 purchase_incourse_list,
                 "choisissez un élément de la liste: ")
             action_choice = Menu.display_menu(
                 menu="second",
                 sentence=
                 "quelle action voulez-vous effectuer sur cet achat ?")
             if action_choice == "continuer":
                 print("vous continuez l'enregistrement de cet achat! ")
                 purchase_id = user_choice[0]
                 Purchase.record_purchase_product(purchase_id)
             elif action_choice == "supprimer":
                 print("vous supprimez cet enregistrement")
                 Purchase.purchase_delete(user_choice[0])
             else:
                 break
             user_pursue = Check.check_yn(
                 "voulez-vous poursuivre a consulter les achats en cours ? "
             )
             if user_pursue == 'n':
                 want_to_continue = False
Пример #32
0
 def display_values(values_list, sentence):
     for ind, elmt in enumerate(values_list):
         print(ind + 1, " - ", end="")
         elmt = elmt[1:]
         print(elmt, sep=", ")
     choice = Check.check_choice_list(values_list, sentence)
     return choice
Пример #33
0
 def __init__(self, name, config):
     Check.__init__(self, name, config)
     self.logger.debug("Initialize webcheck %s %s" % (name, config["url"]))
     self.set_config_default_value("frequency", "5")
     self.set_config_default_value("timeout", "30")
     self.set_config_default_value("response_time", 10)
     self.set_config_default_value("valid_http_codes", "200,301,304") 
     self.set_config_default_value("user_agent", "globcheck") 
     self.set_config_default_value("report_headers", "false") 
     self.set_config_default_value("report_body", "false")
     self.set_config_default_value("cleanup_body", "true") 
     if self.get_config_value("set_headers") != None:
         self.__set_headers = self.get_config_value("set_headers").split("\n")
         for h in self.__set_headers:
             self.logger.debug("set_headers: %s" % h)
     else:
         self.__set_headers = None
     if self.get_config_value("get_headers") != None:
         self.__get_headers = self.get_config_value("get_headers").split(",")
         for h in self.__get_headers:
             self.logger.debug("get_headers: %s" % h)
     else:
         self.__get_headers = None
Пример #34
0
 def __init__(self, name, config):
     Check.__init__(self, name, config)
Пример #35
0
    def __init__(self, filename, config_file, alienvault_config, severity_list, appliance_type_list, ignore_dummy_platform, verbose, raw):
        # Common properties.
        self.__config_file = None
        self.__sections = []
        self.__alienvault_config = {}
        self.__severity_list = []
        self.__appliance_type_list = []
        self.__ignore_dummy_platform = False
        self.__verbose = 0
        self.__raw = False
        self.__name = ''
        self.__id = ''
        self.__description = ''
        self.__type = ''
        self.__exclude = ''
        self.__category = []
        self.__requires = []
        self.__profiles = []
        self.__cutoff = False
        self.__strike_zone = False
        self.__raw_limit = 0
        self.__result = True

        # 'file' type properties.
        self.__filename = ''
        self.__file_must_exist = False
        self.__check_force_true = False

        # 'command' type properties.
        self.__command = ''

        # Shared properties for 'file' and 'command' types.
        self.__data = ''
        self.__data_len = ''

        # 'db' type properties.
        self.__host = ''
        self.__user = ''
        self.__password = ''
        self.__database = ''
        self.__db_conn = None
        self.__db_cursor = None

        # Plugin defined checks.
        self.__checks = []

        self.__config_file = config_file
        self.__alienvault_config = alienvault_config
        self.__severity_list = severity_list
        self.__appliance_type_list = appliance_type_list
        self.__ignore_dummy_platform = ignore_dummy_platform
        self.__verbose = verbose
        self.__raw = raw

        # try:
        #     # Parse the plugin configuration file.
        #     self.__config_file = PluginConfigParser()
        #     self.__config_file.read(filename)
        # except PluginConfigParserError:
        #     raise
        # except Exception as e:
        #     raise PluginError('Cannot parse plugin file "%s": %s' % (filename, str(e)), filename)

        try:
            # Parse 'check' sections.
            self.__sections = self.__config_file.sections()
            self.__name = self.__config_file.get('properties', 'name')
            self.__id = self.__config_file.get('properties', 'id')
            self.__description = self.__config_file.get('properties', 'description')
            self.__type = self.__config_file.get('properties', 'type')
            self.__category = self.__config_file.get('properties', 'category').split(',')

            plugin_data = {'id': self.__id if self.__id else '',
                           'type': self.__type if self.__type else '',
                           'description': self.__description if self.__description else ''}
            if self.__verbose > 0:
                Output.emphasized('\nRunning plugin "%s"...\n' % self.__name, [self.__name])

            if self.__config_file.has_option('properties', 'requires'):
                self.__requires = self.__config_file.get('properties', 'requires').split(';')
                self.__check_requirements__()

            # Check for the 'cutoff' option
            if self.__config_file.has_option('properties', 'cutoff'):
                self.__cutoff = self.__config_file.getboolean('properties', 'cutoff')

            # Check for the 'strike_zone' option
            if self.__config_file.has_option('properties', 'affects_strike_zone'):
                self.__strike_zone = self.__config_file.getboolean('properties', 'affects_strike_zone')

            # Check for the 'file_must_exist' option
            if self.__config_file.has_option('properties', 'file_must_exist'):
                self.__file_must_exist = self.__config_file.getboolean('properties', 'file_must_exist')

            # Check for the 'exclude' option
            if self.__config_file.has_option('properties', 'exclude'):
                self.__exclude = self.__config_file.get('properties', 'exclude').split(',')
                for excluding_profile in self.__exclude:
                    excluding_profile = excluding_profile.strip()
                    if excluding_profile in self.__alienvault_config['hw_profile']:
                        raise PluginError(msg='Plugin cannot be executed in %s' % self.__alienvault_config['hw_profile'],
                                          plugin=self.__name,
                                          plugin_data=plugin_data)

            # Check for the 'limit' option (in kbytes), used in combination with the raw data output. '0' means no limit.
            if self.__raw and self.__config_file.has_option('properties', 'raw_limit'):
                self.__raw_limit = self.__config_file.getint('properties', 'raw_limit')

            # Check for profile & version where this plugin is relevant.
            if self.__config_file.has_option('properties', 'profiles'):
                profiles_versions = self.__config_file.get('properties', 'profiles')
                self.__profiles = [(x.partition(':')[0], x.partition(':')[2]) for x in profiles_versions.split(';')]

                for (profile, version) in self.__profiles:
                    if profile == '' or version == '':
                        raise PluginError(msg='Empty profile or version in "profiles" field',
                                          plugin=self.__name,
                                          plugin_data=plugin_data)

                    if profile not in self.__alienvault_config['sw_profile'] and \
                       profile != self.__alienvault_config['hw_profile']:
                        raise PluginError(msg='Profile "%s" does not match installed profiles' % profile,
                                          plugin=self.__name,
                                          plugin_data=plugin_data)

                    if version.startswith('>'):
                        ret = LooseVersion(self.__alienvault_config['version']) > LooseVersion(version[1:])
                    elif version.startswith('<'):
                        ret = LooseVersion(self.__alienvault_config['version']) < LooseVersion(version[1:])
                    elif version.startswith('=='):
                        ret = LooseVersion(self.__alienvault_config['version']) == LooseVersion(version[2:])
                    elif version.startswith('!='):
                        ret = LooseVersion(self.__alienvault_config['version']) != LooseVersion(version[2:])
                    else:
                        raise PluginError(msg='Profile "%s" version does not match installed profiles' % profile,
                                          plugin=self.__name,
                                          plugin_data=plugin_data)

            # Ugly...
            if self.__type == 'file':
                self.__init_file__()
            elif self.__type == 'command':
                self.__init_command__()
            elif self.__type == 'db':
                self.__init_db__()
            elif self.__type == 'hardware':
                pass
            else:
                raise PluginError(msg='Unknown type',
                                  plugin=self.__name,
                                  plugin_data=plugin_data)

            # Parse 'check' sections.
            sections = self.__config_file.sections()
            for section in sections:
                if section != 'properties':
                    check = Check(self, section)
                    needs_deletion = False
                    if not check.check_appliance_type(self.__alienvault_config['hw_profile'],
                                                      self.__appliance_type_list,
                                                      self.__ignore_dummy_platform):
                        Output.warning("\nCheck %s is not meant to be run in %s" % (section,
                                                                                    self.__alienvault_config['hw_profile']))
                        needs_deletion = True

                    elif not check.check_version(self.__alienvault_config['version']):
                        Output.warning("\nCheck %s cannot be run in version %s" % (section,
                                                                                   self.__alienvault_config['version']))
                        needs_deletion = True

                    elif not check.check_version_type():
                        Output.warning("\nCheck %s is not meant to be run in a %s license" % (section,
                                                                                              self.__alienvault_config['versiontype']))
                        needs_deletion = True
                    if not needs_deletion:
                        self.__checks.append(check)
                    else:
                        del check

        except PluginError:
            raise

        except PluginConfigParserError:
            raise

        except CheckError as e:
            plugin_data = {'id': self.__id if self.__id else '',
                           'type': self.__type if self.__type else '',
                           'description': self.__description if self.__description else ''}
            raise PluginError(msg=e.msg,
                              plugin=e.plugin,
                              plugin_data=plugin_data)

        except Exception as e:
            raise PluginError(msg='%s' % str(e),
                              plugin=filename,
                              plugin_data={})
Пример #36
0
from check import Check

someProxies = """
182.254.153.54:80
117.177.243.53:8080
39.171.108.213:8123
117.177.243.15:8080
180.208.78.49:80
222.88.236.236:843
58.220.2.141:80
58.220.2.140:80
120.198.236.10:80
58.220.2.136:80
58.220.2.133:80
222.88.236.234:81
202.194.96.46:80
180.97.185.35:10001
58.220.2.142:80
116.228.80.186:8080
220.248.224.242:8089
58.220.2.135:80
115.159.5.247:80
111.12.83.27:80
106.38.251.62:8088
203.148.12.132:8000
"""

if __name__ == "__main__":
    ck = Check()
    successProxies = ck.check(someProxies.split('\n'))
    print "\n".join(successProxies)
Пример #37
0
  def __init__ (self, filename, ossim_config, severity_list, verbose, raw):

    # Common properties.
    self.__config_file = None
    self.__ossim_config = None
    self.__severity_list = []
    self.__verbose = 0
    self.__raw = False
    self.__enable = False
    self.__name = ''
    self.__type = ''
    self.__category = []
    self.__requires = []
    self.__profiles = []
    self.__cutoff = False
    self.__raw_limit = 0

    # 'file' type properties.
    self.__filename = ''

    # 'command' type properties.
    self.__command = ''

    # Shared properties for 'file' and 'command' types.
    self.__data = ''
    self.__data_len = ''

    # 'db' type properties.
    self.__host = ''
    self.__user = ''
    self.__password = ''
    self.__database = ''
    self.__db_conn = None
    self.__db_cursor = None

    # Plugin defined checks.
    self.__checks = []

    # Check for file extension.
    if not filename.endswith ('.plg'):
      raise PluginError ('File extension is not .plg', filename)

    self.__ossim_config = ossim_config
    self.__severity_list = severity_list
    self.__verbose = verbose
    self.__raw = raw

    try:
      # Parse the plugin configuration file.
      self.__config_file = PluginConfigParser ()
      self.__config_file.read (filename)
    except Exception as e:
      raise PluginError ('Cannot parse plugin file "%s": %s' % (filename, str(e)), filename)

    # Check first if this plugin is enabled.
    if self.__config_file.has_option('properties', 'enable'):
      self.__enable = eval(self.__config_file.get ('properties', 'enable'))
      if not self.__enable:
        return
    else:
      return

    # Parse for translates.
    # Very inefficient, yes.
    for section in self.__config_file.sections():
      for option, value in self.__config_file.items(section):
        if not option in ['warning', 'advice']:
          for key in self.__ossim_config.keys():
            if key in value:
              new_value = value.replace(key, self.__ossim_config[key])
              self.__config_file.set(section, option, new_value)

    try:
      self.__name = self.__config_file.get ('properties', 'name')
      self.__type = self.__config_file.get ('properties', 'type')
      self.__category = self.__config_file.get ('properties', 'category').split(',')

      if self.__config_file.has_option('properties', 'requires'):
        self.__requires = self.__config_file.get('properties', 'requires').split(';')
        self.__check_requirements__ ()

      # Check for the 'cutoff' option
      if self.__config_file.has_option('properties', 'cutoff'):
        self.__cutoff = eval(self.__config_file.get ('properties', 'cutoff'))

      # Check for the 'limit' option (in kbytes), used in combination with the raw data output. '0' means no limit.
      if self.__raw and self.__config_file.has_option('properties', 'raw_limit'):
        try:
          self.__raw_limit = int(self.__config_file.get ('properties', 'raw_limit'))
        except Exception, e:
          raise PluginError ('"raw_limit" property is not an integer' % profile, self.__name)

      # Check for profile & version where this plugin is relevant.
      if self.__config_file.has_option('properties', 'profiles'):
        profiles_versions = self.__config_file.get ('properties', 'profiles')
        self.__profiles = [tuple (x.split(':')) for x in profiles_versions.split(';')]

        for (i, (profile, version)) in enumerate (self.__profiles):
          if not profile in self.__ossim_config['profiles']:
            raise PluginError ('Profile "%s" does not match installed profiles' % profile, self.__name)

          if version.startswith('>'):
            ret = LooseVersion(self.__ossim_config['versions'][i]) > LooseVersion (version[1:])
          elif version.startswith('<'):
            ret = LooseVersion(self.__ossim_config['versions'][i]) < LooseVersion (version[1:])
          elif version.startswith('=='):
            ret = LooseVersion(self.__ossim_config['versions'][i]) == LooseVersion (version[2:])
          elif version.startswith('!='):
            ret = LooseVersion(self.__ossim_config['versions'][i]) != LooseVersion (version[2:])
          else:
            ret = False

          if not ret:
            raise PluginError ('Profile "%s" version does not match installed profiles' % profile, self.__name)

      # Ugly...
      if self.__type == 'file':
        self.__init_file__ ()
      elif self.__type == 'command':
        self.__init_command__ ()
      elif self.__type == 'db':
        self.__init_db__ ()
      else:
        raise PluginError ('Unknown type', self.__name)

      # Parse 'check' sections.
      sections = self.__config_file.sections()
      for section in sections:
        if section != 'properties':
          check = Check (self, section, self.__verbose)
          if check.check_severity (self.__severity_list):
            self.__checks.append (check)
          else:
            del check
Пример #38
0
 def __init__(self, name, config):
     Check.__init__(self, name, config)
     self.url = config["host"]
     self.frequency = 5
     self.timeout = 1000
Пример #39
0
def main(args, config):
    
    originalPath= os.getcwd()
    fasta_file = os.path.join(os.getcwd(),args.fasta_file)
    profilePath = os.path.join(os.getcwd(),'profiles')
    wDir = os.path.join(os.getcwd(), datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
    os.mkdir(wDir)      
    os.chdir(wDir)
    
    #add a check module
    fileWork = os.path.join(os.getcwd(),'final_sequences.fasta')
    validFile = Check(fasta_file, args, config)
    validFile.lenFasta()
    validFile.reverseFile()
    validFile.makeLog()
    
    
    if int(args.mode) == 1:
        basicMode(config, fasta_file, profilePath)
        
    if int(args.mode) == 2:   
        newConfig = config.copy()
        dfCompare = os.path.join(originalPath, args.compare)
        
        
        xList = []
        yList = []
        countResults = OrderedDict()
        for i,j in config.items():
            if type(j) is list:
                label = i
                valStart= j[0]
                valStop= j[1]
                valStep= j[2]
                
                k = valStart
                while k <= float(valStop):
                    newConfig[i] = k
                    folder = i + str(k)
                    subDir = os.path.join(wDir, folder)
                    os.mkdir(subDir)
                    os.chdir(subDir)
                    if i == 'win_length':
                        newConfig['win_step'] = k
                    
                    configFile(newConfig)
                    basicMode(newConfig, fasta_file, profilePath)
                    
                    result, trueEvents, times, baseEvents, seqDict = compareResults(dfCompare)
                    xList.append(k)
                    yList.append(result)
                    countResults[k] = times
    
                    baseReport(countResults, label, baseEvents, config['win_length'], seqDict)                       
                    
                    k = k + valStep     
                    os.chdir('..')
                        
                    
        graph(xList, yList, label, trueEvents)
        #print xList
        #print yList
        #print countResults
        baseReport(countResults, label, baseEvents, config['win_length'], seqDict)