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
Ejemplo n.º 2
0
 def __init__(self, charid, charname, x=0.0, y=0.0, zone=0):
     super(AIObot, self).__init__(
         None,
         random.choice([
             "ur mom gay", "go commit die", "beep boop", "i'm a bot", "69",
             "vali sucks"
         ]))
     self.x = x
     self.y = y
     self.zone = zone
     self.ready = True
     self.CharID = charid
     self.charname = charname
     self.sprite = charname + "\\spin"
     self.char_ini = IniConfig("data/characters/" + charname + "/char.ini")
     self.imgprefix = self.char_ini.get("Options", "imgprefix", "")
     if self.imgprefix:
         self.imgprefix += "-"
     self.blip = self.char_ini.get("Options", "blip", "male")
     walkanimlen = int(self.char_ini.get("WalkAnims", "total", 1))
     self.walkanims = [
         self.char_ini.get("WalkAnims", str(i + 1), "walk")
         for i in range(walkanimlen + 1)
     ]
     self.runanim = int(self.char_ini.get("WalkAnims", "runanim", 1)) - 1
     self.setMovement(False)
Ejemplo n.º 3
0
def test_iniconfig_from_file(tmpdir):
    path = tmpdir/'test.txt'
    path.write('[metadata]\nname=1')

    config = IniConfig(path=path)
    assert list(config.sections) == ['metadata']
    config = IniConfig(path, "[diff]")
    assert list(config.sections) == ['diff']
    py.test.raises(TypeError, "IniConfig(data=path.read())")
Ejemplo n.º 4
0
def test_iniconfig_from_file(tmpdir):
    path = tmpdir / "test.txt"
    path.write("[metadata]\nname=1")

    config = IniConfig(path=path)
    assert list(config.sections) == ["metadata"]
    config = IniConfig(path, "[diff]")
    assert list(config.sections) == ["diff"]
    with pytest.raises(TypeError):
        IniConfig(data=path.read())
Ejemplo n.º 5
0
class Config(IniConfig):

    # general
    language = IniConfig.iniproperty('general', 'language', 'es')  # es or en

    # web-radio
    favorites = IniConfig.iniproperty('web-radio', 'favorites', [
        'http://streaming3.radiocat.net:80/',
        'http://streams.90s90s.de/main/mp3-192/streams.90s90s.de/'
    ])
    recents = IniConfig.iniproperty('web-radio', 'recents', [
        'http://streaming3.radiocat.net:80/',
        'http://streams.90s90s.de/main/mp3-192/streams.90s90s.de/'
    ])
    maxrecents = IniConfig.iniproperty('web-radio', 'maxrecents', 25)

    # wifi
    wifi_ssid = IniConfig.iniproperty('wifi', 'ssid', 'demo')
    wifi_password = IniConfig.iniproperty('wifi', 'password', 'demo')

    # mpd
    mpd_host = IniConfig.iniproperty('mpd', 'host', 'localhost')
    mpd_port = IniConfig.iniproperty('mpd', 'port', 6600)
    mpd_timeout = IniConfig.iniproperty(
        'mpd', 'timeout',
        10)  # network timeout in seconds (floats allowed), default: None
    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
Ejemplo n.º 7
0
def test_example_pypirc():
    config = IniConfig(
        "pypirc",
        data=dedent("""
        [distutils]
        index-servers =
            pypi
            other

        [pypi]
        repository: <repository-url>
        username: <username>
        password: <password>

        [other]
        repository: http://example.com/pypi
        username: <username>
        password: <password>
    """),
    )
    distutils, pypi, other = list(config)
    assert distutils["index-servers"] == "pypi\nother"
    assert pypi["repository"] == "<repository-url>"
    assert pypi["username"] == "<username>"
    assert pypi["password"] == "<password>"
    assert ["repository", "username", "password"] == list(other)
Ejemplo n.º 8
0
 def __init__(self, charid, charname, x=0.0, y=0.0, zone=0):
     super(AIObot, self).__init__(None, "BOT")
     self.x = x
     self.y = y
     self.zone = zone
     self.ready = True
     self.CharID = charid
     self.charname = charname
     self.sprite = charname+"/spin.gif"
     self.char_ini = IniConfig("data/characters/"+charname+"/char.ini")
     self.imgprefix = self.char_ini.get("Options", "imgprefix", "")
     if self.imgprefix:
         self.imgprefix += "-"
     self.blip = self.char_ini.get("Options", "blip", "male")
     walkanimlen = int(self.char_ini.get("WalkAnims", "total", 1))
     self.walkanims = [self.char_ini.get("WalkAnims", str(i+1), "walk") for i in range(walkanimlen+1)]
     self.runanim = int(self.char_ini.get("WalkAnims", "runanim", 1))-1
     self.setMovement(False)
Ejemplo n.º 9
0
def test_config_contains():
    config = IniConfig("x.ini", data=dedent('''
          [section1]
          value=1
          [section2]
          value=2
    '''))
    assert 'xyz' not in config
    assert 'section1' in config
    assert 'section2' in config
Ejemplo n.º 10
0
def test_config_iter():
    config = IniConfig("x.ini", data=dedent('''
          [section1]
          value=1
          [section2]
          value=2
    '''))
    l = list(config)
    assert len(l) == 2
    assert l[0].name == 'section1'
    assert l[0]['value'] == '1'
    assert l[1].name == 'section2'
    assert l[1]['value'] == '2'
Ejemplo n.º 11
0
def test_config_contains():
    config = IniConfig(
        "x.ini",
        data=dedent("""
          [section1]
          value=1
          [section2]
          value=2
    """),
    )
    assert "xyz" not in config
    assert "section1" in config
    assert "section2" in config
Ejemplo n.º 12
0
def determine_setup(
    inifile: Optional[str],
    args: List[str],
    rootdir_cmd_arg: Optional[str] = None,
    config: Optional["Config"] = None,
) -> Tuple[py.path.local, Optional[str], Any]:
    dirs = get_dirs_from_args(args)
    if inifile:
        iniconfig = IniConfig(inifile)
        is_cfg_file = str(inifile).endswith(".cfg")
        sections = ["tool:pytest", "pytest"] if is_cfg_file else ["pytest"]
        for section in sections:
            try:
                inicfg = iniconfig[
                    section]  # type: Optional[py.iniconfig._SectionWrapper]
                if is_cfg_file and section == "pytest" and config is not None:
                    fail(CFG_PYTEST_SECTION.format(filename=str(inifile)),
                         pytrace=False)
                break
            except KeyError:
                inicfg = None
        if rootdir_cmd_arg is None:
            rootdir = get_common_ancestor(dirs)
    else:
        ancestor = get_common_ancestor(dirs)
        rootdir, inifile, inicfg = getcfg([ancestor], config=config)
        if rootdir is None and rootdir_cmd_arg is None:
            for possible_rootdir in ancestor.parts(reverse=True):
                if possible_rootdir.join("setup.py").exists():
                    rootdir = possible_rootdir
                    break
            else:
                if dirs != [ancestor]:
                    rootdir, inifile, inicfg = getcfg(dirs, config=config)
                if rootdir is None:
                    if config is not None:
                        cwd = config.invocation_dir
                    else:
                        cwd = py.path.local()
                    rootdir = get_common_ancestor([cwd, ancestor])
                    is_fs_root = os.path.splitdrive(str(rootdir))[1] == "/"
                    if is_fs_root:
                        rootdir = ancestor
    if rootdir_cmd_arg:
        rootdir = py.path.local(os.path.expandvars(rootdir_cmd_arg))
        if not rootdir.isdir():
            raise UsageError(
                "Directory '{}' not found. Check your '--rootdir' option.".
                format(rootdir))
    return rootdir, inifile, inicfg or {}
Ejemplo n.º 13
0
def test_iter_file_order():
    config = IniConfig("x.ini", data="""
[section2] #cpython dict ordered before section
value = 1
value2 = 2 # dict ordered before value
[section]
a = 1
b = 2
""")
    l = list(config)
    secnames = [x.name for x in l]
    assert secnames == ['section2', 'section']
    assert list(config['section2']) == ['value', 'value2']
    assert list(config['section']) == ['a', 'b']
Ejemplo n.º 14
0
    def properties(cls, env: str):
        config = IniConfig(cls._config_file)
        environments = (Environments.DEV, Environments.PROD)

        if env not in environments:
            message = f'[{env}] is not supported. Supported environments {environments}'
            log.error(message)
            raise UnsupportedEnvironmentError(message)

        if env == Environments.DEV:
            return cls._dev(*config.sections.get(env).values())

        if env == Environments.PROD:
            return cls._prod(*config.sections.get(env).values())
Ejemplo n.º 15
0
def test_config_iter():
    config = IniConfig(
        "x.ini",
        data=dedent("""
          [section1]
          value=1
          [section2]
          value=2
    """),
    )
    l = list(config)
    assert len(l) == 2
    assert l[0].name == "section1"
    assert l[0]["value"] == "1"
    assert l[1].name == "section2"
    assert l[1]["value"] == "2"
Ejemplo n.º 16
0
def test_iter_file_order():
    config = IniConfig(
        "x.ini",
        data="""
[section2] #cpython dict ordered before section
value = 1
value2 = 2 # dict ordered before value
[section]
a = 1
b = 2
""",
    )
    l = list(config)
    secnames = [x.name for x in l]
    assert secnames == ["section2", "section"]
    assert list(config["section2"]) == ["value", "value2"]
    assert list(config["section"]) == ["a", "b"]
Ejemplo n.º 17
0
def test_iniconfig_lineof():
    config = IniConfig(
        "x.ini",
        data=("[section]\n" "value = 1\n" "[section2]\n" "# comment\n" "value =2"),
    )

    assert config.lineof("missing") is None
    assert config.lineof("section") == 1
    assert config.lineof("section2") == 3
    assert config.lineof("section", "value") == 2
    assert config.lineof("section2", "value") == 5

    assert config["section"].lineof("value") == 2
    assert config["section2"].lineof("value") == 5
Ejemplo n.º 18
0
def test_iniconfig_lineof():
    config = IniConfig("x.ini", data=(
        '[section]\n'
        'value = 1\n'
        '[section2]\n'
        '# comment\n'
        'value =2'
    ))

    assert config.lineof('missing') is None
    assert config.lineof('section') == 1
    assert config.lineof('section2') == 3
    assert config.lineof('section', 'value') == 2
    assert config.lineof('section2', 'value') == 5

    assert config['section'].lineof('value') == 2
    assert config['section2'].lineof('value') == 5
Ejemplo n.º 19
0
def getcfg(args, config=None):
    """
    Search the list of arguments for a valid ini-file for pytest,
    and return a tuple of (rootdir, inifile, cfg-dict).

    note: config is optional and used only to issue warnings explicitly (#2891).
    """
    inibasenames = ["pytest.ini", "tox.ini", "setup.cfg"]
    args = [x for x in args if not str(x).startswith("-")]
    if not args:
        args = [py.path.local()]
    for arg in args:
        arg = py.path.local(arg)
        for base in arg.parts(reverse=True):
            for inibasename in inibasenames:
                p = base.join(inibasename)
                if exists(p):
                    try:
                        iniconfig = IniConfig(p)
                    except ParseError as exc:
                        raise UsageError(str(exc))

                    if (inibasename == "setup.cfg"
                            and "tool:pytest" in iniconfig.sections):
                        return base, p, iniconfig["tool:pytest"]
                    elif "pytest" in iniconfig.sections:
                        if inibasename == "setup.cfg" and config is not None:

                            fail(
                                CFG_PYTEST_SECTION.format(
                                    filename=inibasename),
                                pytrace=False,
                            )
                        return base, p, iniconfig["pytest"]
                    elif inibasename == "pytest.ini":
                        # allowed to be empty
                        return base, p, {}
    return None, None, None
Ejemplo n.º 20
0
def test_example_pypirc():
    config = IniConfig("pypirc", data=dedent('''
        [distutils]
        index-servers =
            pypi
            other

        [pypi]
        repository: <repository-url>
        username: <username>
        password: <password>

        [other]
        repository: http://example.com/pypi
        username: <username>
        password: <password>
    '''))
    distutils, pypi, other = list(config)
    assert distutils["index-servers"] == "pypi\nother"
    assert pypi['repository'] == '<repository-url>'
    assert pypi['username'] == '<username>'
    assert pypi['password'] == '<password>'
    assert ['repository', 'username', 'password'] == list(other)
Ejemplo n.º 21
0
def main(argv):
    section = ''
    recursive = False

    logLevel = logging.WARNING

    total_files = 0
    total_replacements = 0

    logging.basicConfig(level=logLevel, format='%(levelname)s: %(message)s')

    pathsCache = Cache()

    path = Path(cache = pathsCache)
    configPath = Path(cache = pathsCache)

    try:
        opts, args = getopt.getopt(argv, 'hrs:p:c:',
                ['help', 'recursive', 'section=', 'path=', 'config='])
    except getopt.GetoptError as detail:
        logging.error(detail)
    else:
        for opt, arg in opts:
            if opt in ('-h', '--help'):
                print __doc__
                sys.exit(0)

            elif opt in ('-r', '--recursive'):
                recursive = True

            elif opt in ('-s', '--section'):
                section = arg

            elif opt in ('-p', '--path'):
                path.setPath(arg)

            elif opt in ('-c', '--config'):
                configPath.setPath(arg)

    if not section:
        logging.error(err.err_msg.format(3, err.error[3]))
        sys.exit(1)

    if not path.exists():
        logging.error(err.err_msg.format(1, err.error[1].format('path',
            path.getPath())))
        sys.exit(1)

    if not path.hasRights(True, True):
        logging.error(err.err_msg.format(2, err.error[2].format(path.getPath(),
            'read and write')))
        sys.exit(1)

    if not configPath.exists():
        logging.error(err.err_msg.format(1, err.error[1].format('config path',
            configPath.getPath())))
        sys.exit(1)

    if not configPath.hasRights():
        logging.error(err.err_msg.format(2,
            err.error[2].format(configPath.getPath(), 'read')))
        sys.exit(1)

    configFile = IniConfig(configPath)

    try:
        tokens = configFile.parse(section)
    except ConfigParser.NoSectionError:
        logging.error(err.err_msg.format(5, err.error[5].format(section)))
        sys.exit(1)

    if not tokens:
        logging.error(err.err_msg.format(4,
            err.error[4].format(section, configPath.getPath())))
        sys.exit(1)

    starting(section=section, path=path.getPath(), config=configPath.getPath(),
            r = recursive)

    if os.path.isdir(path.getPath()):
        fileCollection = path.getFilesByMime('text', recursive)

    else:
        fileCollection = RunCollection(File(path))

    if fileCollection:
        total_files = fileCollection.countItems()
        total_replacements = fileCollection.map(File.replace, postponeException = False, tokens = tokens)

    ending(total_replacements[0], total_files)
Ejemplo n.º 22
0
def test_section_iter():
    config = IniConfig("x", data="[section]\nvalue=1")
    names = list(config["section"])
    assert names == ["value"]
    items = list(config["section"].items())
    assert items == [("value", "1")]
Ejemplo n.º 23
0
def test_section_getitem():
    config = IniConfig("x", data="[section]\nvalue=1")
    assert config["section"]["value"] == "1"
    assert config["section"]["value"] == "1"
Ejemplo n.º 24
0
def test_section_get():
    config = IniConfig("x", data="[section]\nvalue=1")
    section = config["section"]
    assert section.get("value", convert=int) == 1
    assert section.get("value", 1) == "1"
    assert section.get("missing", 2) == 2
Ejemplo n.º 25
0
def test_iniconfig_get_missing():
    config = IniConfig("x", data="[section]\nint = 1\nfloat = 1.1")
    assert config.get("section", "missing", default=1) == 1
    assert config.get("section", "missing") is None
Ejemplo n.º 26
0
def test_iniconfig_get_convert():
    config = IniConfig("x", data="[section]\nint = 1\nfloat = 1.1")
    assert config.get("section", "int") == "1"
    assert config.get("section", "int", convert=int) == 1
Ejemplo n.º 27
0
def test_iniconfig_duplicate_key_fails():
    with pytest.raises(ParseError) as excinfo:
        IniConfig("x", data="[section]\nname = Alice\nname = bob")

    assert "duplicate name" in str(excinfo.value)
Ejemplo n.º 28
0
def test_iniconig_section_duplicate_fails():
    with pytest.raises(ParseError) as excinfo:
        IniConfig("x", data="[section]\n[section]")
    assert "duplicate section" in str(excinfo.value)
Ejemplo n.º 29
0
def test_parse_empty():
    parsed = parse("")
    assert not parsed
    ini = IniConfig("sample", "")
    assert not ini.sections
Ejemplo n.º 30
0
def test_missing_section():
    config = IniConfig("x", data="[section]\nvalue=1")
    with pytest.raises(KeyError):
        config["other"]
Ejemplo n.º 31
0
class AIObot(AIOplayer):
    char_ini = None
    charname = ""
    imgprefix = ""
    walkanims = []
    runanim = 0
    blip = ""
    type = "wander"
    interact = None

    def __init__(self, charid, charname, x=0.0, y=0.0, zone=0):
        super(AIObot, self).__init__(
            None,
            random.choice([
                "ur mom gay", "go commit die", "beep boop", "i'm a bot", "69",
                "vali sucks"
            ]))
        self.x = x
        self.y = y
        self.zone = zone
        self.ready = True
        self.CharID = charid
        self.charname = charname
        self.sprite = charname + "\\spin"
        self.char_ini = IniConfig("data/characters/" + charname + "/char.ini")
        self.imgprefix = self.char_ini.get("Options", "imgprefix", "")
        if self.imgprefix:
            self.imgprefix += "-"
        self.blip = self.char_ini.get("Options", "blip", "male")
        walkanimlen = int(self.char_ini.get("WalkAnims", "total", 1))
        self.walkanims = [
            self.char_ini.get("WalkAnims", str(i + 1), "walk")
            for i in range(walkanimlen + 1)
        ]
        self.runanim = int(self.char_ini.get("WalkAnims", "runanim", 1)) - 1
        self.setMovement(False)

    def point_distance(self, x1, y1, x2, y2):
        return ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2))

    def player_thread(self):
        wandertick = 0
        while True:
            if self.close:
                thread.exit()

            if not self.interact:
                continue

            if self.type == "follow":
                dist = self.point_distance(self.x, self.y, self.interact.x,
                                           self.interact.y)
                if dist < 512:
                    self.setMovement(False)
                else:
                    run = int(dist >= 768)
                    if self.x > self.interact.x and self.y > self.interact.y:
                        dir_nr = AIOprotocol.NORTHWEST
                    elif self.x < self.interact.x and self.y > self.interact.y:
                        dir_nr = AIOprotocol.NORTHEAST
                    elif self.x > self.interact.x and self.y < self.interact.y:
                        dir_nr = AIOprotocol.SOUTHWEST
                    elif self.x < self.interact.x and self.y < self.interact.y:
                        dir_nr = AIOprotocol.SOUTHEAST
                    elif self.x < self.interact.x:
                        dir_nr = AIOprotocol.EAST
                    elif self.x > self.interact.x:
                        dir_nr = AIOprotocol.WEST
                    elif self.y > self.interact.y:
                        dir_nr = AIOprotocol.NORTH
                    elif self.y < self.interact.y:
                        dir_nr = AIOprotocol.SOUTH

                    self.setMovement(True, dir_nr, run)

            elif self.type == "wander":
                if wandertick:
                    wandertick -= 1
                else:

                    if self.isMoving():
                        wandertick = random.randint(10, 25)
                    else:
                        wandertick = random.randint(30, 60)

                    self.setMovement(not self.isMoving(), random.randint(0, 7),
                                     0)

            else:
                self.setMovement(False)

            self.x += self.hspeed
            self.y += self.vspeed
            time.sleep(1. / 30)

    def setMovement(self, move, dir_nr=0, run=0):
        if not move:
            self.hspeed = 0
            self.vspeed = 0
            self.sprite = self.charname + "\\spin"
            return

        self.dir_nr = dir_nr
        self.run = run
        if not run:
            spd = 3
            ind = 0
        else:
            spd = 6
            ind = self.runanim

        if dir_nr == 0:  #south
            self.hspeed = 0
            self.vspeed = spd
            self.sprite = self.charname + "\\" + self.walkanims[ind] + "south"
        if dir_nr == 1:  #southwest
            self.hspeed = -spd
            self.vspeed = spd
            self.sprite = self.charname + "\\" + self.walkanims[
                ind] + "southwest"
        if dir_nr == 2:  #west
            self.hspeed = -spd
            self.vspeed = 0
            self.sprite = self.charname + "\\" + self.walkanims[ind] + "west"
        if dir_nr == 3:  #northwest
            self.hspeed = -spd
            self.vspeed = -spd
            self.sprite = self.charname + "\\" + self.walkanims[
                ind] + "northwest"
        if dir_nr == 4:  #north
            self.hspeed = 0
            self.vspeed = -spd
            self.sprite = self.charname + "\\" + self.walkanims[ind] + "north"
        if dir_nr == 5:  #northeast
            self.hspeed = spd
            self.vspeed = -spd
            self.sprite = self.charname + "\\" + self.walkanims[
                ind] + "northeast"
        if dir_nr == 6:  #east
            self.hspeed = spd
            self.vspeed = 0
            self.sprite = self.charname + "\\" + self.walkanims[ind] + "east"
        if dir_nr == 7:  #southeast
            self.hspeed = spd
            self.vspeed = spd
            self.sprite = self.charname + "\\" + self.walkanims[
                ind] + "southeast"
class Controller:
    """ Program flow controller """

    def __init__(self):
        """ init """

        self.opts = None        # All options for nessus-helper
        self.ini = None         # ini-configuration data

        return

    def getOptions(self):
        """ Get additional options and values """

        # nessus
        if not self.opts['nessus_host']:
            self.opts['nessus_host'] = self.ini.config.get('nessus', 'host')
            self.opts['nessus_port'] = self.ini.config.get('nessus', 'port')
        self.opts['nessus_url'] = Wrapper.buildUrl(self.opts['nessus_host'],
                self.opts['nessus_port'])
        self.opts['nessus_login'] = self.getNessusLogin()
        self.opts['nessus_chapters'] = self.ini.config.get('nessus', 'chapters')

        # smtp
        self.opts['smtp_login'] = {}
        self.opts['smtp_login']['user'] = self.ini.config.get('mail', 'user')
        self.opts['smtp_login']['pass'] = self.ini.config.get('mail', 'pass')
        self.opts['smtp_host'] = self.ini.config.get('mail', 'host')
        self.opts['smtp_port'] = self.ini.config.get('mail', 'port')
        self.opts['smtp_from'] = self.ini.config.get('mail', 'from')

        # addressbook
        self.opts['addrbook'] = self.ini.config.options('addressbook')

        return

    def getNessusLogin(self):
        """ get Nessus login from cmdline or read from ini config file """

        login = {}

        if self.opts['nessus_login']:
            login['user'] = self.opts['nessus_login'].split(':')[0]
            login['pass'] = self.opts['nessus_login'].split(':')[1]
        elif self.ini.config['nessus']:
            login['user'] = self.ini.config.get('nessus', 'user')
            login['pass'] = self.ini.config.get('nessus', 'pass')
        else:
            Wrapper.error('no login specified')

        return login

    def sendReports(self, option):
        """ Send out reports via email """

        msg = {}        # mail header and body
        mail = ''
        server = {}     # smtp server
        m = Mail()

        # smtp server address and tcp port
        server['addr'] = self.opts['smtp_host']
        server['port'] = self.opts['smtp_port']

        # smtp (static content) read from ini file
        msg['from'] = self.opts['smtp_from']

        Wrapper.msg('Sending out reports')

        if option == 'report':
            # for each report in report directory except summary.txt
            for f in os.listdir(self.opts['outdir'] + '/' + TODAY):
                if f != 'summary.txt':
                    report = self.opts['outdir'] + '/' + TODAY + '/' + f
                    name = f.split('.')[0]

                    # mail header + body
                    msg['message'] = 'Hi,\n\nplease find attached the Nessus ' \
                            'report for this week.\n\nBest Regards,\n\n' \
                            "Rocket Internet's Security Team"
                    msg['subject'] = '[{0}] Your new Nessus report for {1} ' \
                            'is ready'.format(name, TODAY)
                    msg['to'] = self.ini.config.get('addressbook', name)

                    # build and send mail
                    mail = m.buildMail(msg, (report,))
                    m.sendMail(server, mail, self.opts['smtp_login'], tls=True)
        else:
            report = self.opts['outdir'] + '/' + TODAY + '/' + 'summary.txt'
            with open(report, 'r') as f:
                report_data = f.read()

            # mail header + body
            msg['message'] = 'Hi,\n\nplease find below the Nessus ' \
                    'Summary Report for this week:\n\n'
            msg['message'] += report_data
            msg['message'] += "\n\nBest Regards,\n\nRocket Internet's " \
                    "Security Team"
            msg['subject'] = 'Nessus Summary Report ({0})'.format(TODAY)
            msg['to'] = self.ini.config.get('addressbook', 'Summary')

            # build and send mail
            mail = m.buildMail(msg, (report,))
            m.sendMail(server, mail, self.opts['smtp_login'], tls=True)

        return

    def processReports(self, option):
        """ Login to nessus, export and download nessus- or summary-reports """

        names = []

        Wrapper.msg('Login to Nessus on ' + "'" + self.opts['nessus_url'] + "'")
        nessus = Nessus(self.opts['nessus_url'])
        nessus.login(self.opts['nessus_login']['user'],
                self.opts['nessus_login']['pass'])
        if not nessus.login:
            Wrapper.error('Cannot login in to Nessus')

        # get scan lists
        Wrapper.msg('Fetching the scan lists')
        scan_list = nessus.getScanList()

        # export and download nessus reports
        if option == 'report':
            Wrapper.msg('Exporting and downloading reports')
            outdir = Wrapper.makeReportDir(self.opts['outdir'])

            for scan in scan_list['scans']:
                if scan['name'] in self.opts['addrbook']:
                    if scan['status'] == 'completed':
                        scan_details = nessus.getScan(scan['id'])
                        end_date = datetime.datetime.fromtimestamp(
                                int(scan_details['info']['scan_end'])
                                ).strftime('%Y-%m-%d')
                        if end_date == TODAY or end_date == YESTERDAY:
                            for root, dirs, files in os.walk(
                                    self.opts['outdir'] + '/' + YESTERDAY):
                                names.append(files)
                            for root, dirs, files in os.walk(
                                    self.opts['outdir'] + '/' + TODAY):
                                names.append(files)
                            names = [i for sublist in names for i in sublist]

                            if scan['name'] + '.html' not in names:
                                file_id = nessus.exportScanResult(scan['id'],
                                        self.opts['format'],
                                        self.opts['nessus_chapters'])['file']

                                # wait before downloading reports if status is
                                # not OK
                                if not nessus.exportStatusCheck(scan['id'],
                                        file_id):
                                    time.sleep(int(self.opts['sleep']))

                                nessus.downloadReport(scan['id'], file_id,
                                        self.opts['format'], scan['name'],
                                        outdir)
        # create and download summary
        else:
            Wrapper.msg('Creating the summary report')
            outdir = Wrapper.makeReportDir(self.opts['outdir'])

            for scan in scan_list['scans']:
                if scan['name'] in self.opts['addrbook']:
                    if scan['status'] == 'completed':
                        scan_res = nessus.getScan(scan['id'])
                        for h in range(len(scan_res['hosts'])):
                            host_id = scan_res['hosts'][h]['host_id']
                            res = nessus.getHostDetails(scan['id'], host_id)
                            for r in res['vulnerabilities']:
                                # critical, high, medium
                                if r['severity'] in (4, 3, 2):
                                    with open(os.path.join(outdir, 'summary.txt'), 'a') as f:
                                        f.write('project: ' + scan['name'] +
                                                ' host: ' + r['hostname'] +
                                                ' issue: ' + r['plugin_name'] + '\n')


        # logout of nessus
        Wrapper.msg('Logout of nessusd')
        nessus.logout()

        return

    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

    def end(self):
        """ Epilog """

        Wrapper.msg('Game Over')

        return
Ejemplo n.º 33
0
def test_iniconfig_section_first(tmpdir):
    with pytest.raises(ParseError) as excinfo:
        IniConfig("x", data="name=1")
    assert excinfo.value.msg == "no section header defined"