Beispiel #1
0
    def save_private_report(self, username, a_token, report_name, report_pass,
                            flag):

        wrapper = Wrapper(self.host, self.port)

        if not wrapper.check_connection():
            cquit(Status.DOWN, "Backend connection error!")

        report_data = report_template % (random.randint(
            100, 1000), username, str(round(
                time.time())), 'private', random.randint(100, 1000), flag)

        Report = {
            'Name': report_name,
            'Type': 'private',
            'Password': report_pass,
            'Data': report_data
        }

        result, errno = wrapper.save_report(username, a_token, Report)

        if errno == err.REPORT_NOT_SAVED:
            cquit(Status.MUMBLE, "Could not save private report!")

        if errno != err.SAVE_REPORT_SUCCESS:
            cquit(Status.MUMBLE, "Could not save private report!")
Beispiel #2
0
class Waiter(object):
    """waiter"""

    def __init__(self):
        self.wrap = Wrapper()

    def add_order(self, waiter_id, order_data):
        """must put waiter id and tickets in list of dict
        [{"id_dish": 1, "count": 1},{"id_dish": 12, "count": 1}..."""
        date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        order = {"id_status": 4,
               "id_user": waiter_id,
               "date": date
                }
        order_id = self.wrap.insert(order, "orders")
        for ticket in order_data:
            ticket["id_order"] = order_id
            try:
                del ticket["image"]
                del ticket["name"]
                del ticket["id"]
                del ticket["description"]
                del ticket["id_category"]

            except Exception, e:
                print e

            self.wrap.insert(ticket, "tickets")
        return order_id
    def checkArgc():
        """ Check argument count """

        if len(sys.argv) == 1:
            Wrapper.error('-H for help and usage')

        return
Beispiel #4
0
def _PostRepoUpgrade(manifest, quiet=False):
    wrapper = Wrapper()
    if wrapper.NeedSetupGnuPG():
        wrapper.SetupGnuPG(quiet)
    for project in manifest.projects:
        if project.Exists:
            project.PostRepoUpgrade()
    def sendRequest(self, method, resource, data='', token='', verify=False):
        """ Send a request to nessus based on the specified data """

        resource = self.url + resource
        headers = { 'X-Cookie': 'token={0}'.format(self.token),
                    'Content-Type': 'application/json' }
        data = json.dumps(data)

        if method == 'POST':
            r = requests.post(resource, data=data, headers=headers,
                    verify=verify)
        elif method == 'PUT':
            r = requests.put(resource, data=data, headers=headers,
                    verify=verify)
        elif method == 'DELETE':
            r = requests.delete(resource, data=data, headers=headers,
                    verify=verify)
        else:
            r = requests.get(resource, params=data, headers=headers,
                    verify=verify)

        if r.status_code != 200:
            e = r.json()
            Wrapper.error(e['error'])

        if 'download' in resource:
            return r.content
        # temp dirty fix. TODO: make it better
        elif 'session' in resource and method == 'DELETE':
            return
        else:
            return r.json()

        return
Beispiel #6
0
class Events(object):

    table_name = "Events"

    def __init__(self):
        self.w = Wrapper()

    def add_event(self, description, id_event_type, id_order, id_customer):
        curdate = strftime("%Y-%m-%d %H:%M:%S", gmtime())
        return self.w.insert(
            {
                "description": description,
                "date": curdate,
                "id_event_type": id_event_type,
                "id_order": id_order,
                "id_customer": id_customer
            }, self.table_name)

    def add_event_no_order(self, description, id_event_type, id_customer):
        curdate = strftime("%Y-%m-%d %H:%M:%S", gmtime())
        return self.w.insert(
            {
                "description": description,
                "date": curdate,
                "id_event_type": id_event_type,
                "id_customer": id_customer
            }, self.table_name)
Beispiel #7
0
 def __init__(self, parent = None, settings_path = ""):
     super(ScudCloud, self).__init__(parent)
     self.setWindowTitle('ScudCloud')
     self.settings_path = settings_path
     self.notifier = Notifier(Resources.APP_NAME, Resources.get_path('scudcloud.png'))
     self.settings = QSettings(self.settings_path + '/scudcloud.cfg', QSettings.IniFormat)
     self.identifier = self.settings.value("Domain")
     if Unity is not None:
         self.launcher = Unity.LauncherEntry.get_for_desktop_id("scudcloud.desktop")
     else:
         self.launcher = DummyLauncher(self)
     self.webSettings()
     self.leftPane = LeftPane(self)
     webView = Wrapper(self)
     webView.page().networkAccessManager().setCookieJar(self.cookiesjar)
     self.stackedWidget = QtGui.QStackedWidget()
     self.stackedWidget.addWidget(webView)
     centralWidget = QtGui.QWidget(self)
     layout = QtGui.QHBoxLayout()
     layout.setContentsMargins(0, 0, 0, 0)
     layout.setSpacing(0)
     layout.addWidget(self.leftPane)
     layout.addWidget(self.stackedWidget)
     centralWidget.setLayout(layout)
     self.setCentralWidget(centralWidget)
     self.addMenu()
     self.tray = Systray(self)
     self.systray(ScudCloud.minimized)
     self.installEventFilter(self)
     if self.identifier is None:
         webView.load(QtCore.QUrl(Resources.SIGNIN_URL))
     else:
         webView.load(QtCore.QUrl(self.domain()))
     webView.show()
Beispiel #8
0
    def __init__(self, window, builder, reddit_info, use_stylesheet=True):
        self.window = window
        self.builder = builder

        if use_stylesheet:
            filename = 'style.css'
            style = Gtk.CssProvider()
            with open(filename, 'r') as file:
                cssData = file.read().encode()

            style.load_from_data(cssData)

            Gtk.StyleContext.add_provider_for_screen(
                Gdk.Screen.get_default(), style,
                Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

        self.random_tmp = ''.join(
            random.choice(string.ascii_uppercase + string.digits)
            for i in range(6))
        self.directory = '/tmp/cobreddit_' + self.random_tmp
        if not os.path.exists(self.directory):
            os.makedirs(self.directory)

        self.reddit = Wrapper(reddit_info)

        self.builder.connect_signals({
            "destroy": self.onDestroy,
            "viewSub": self.view_sub
        })

        self.setup_stack()

        self.view_sub('aww')
    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 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
Beispiel #11
0
def _PostRepoFetch(rp, repo_verify=True, verbose=False):
  if rp.HasChanges:
    print('info: A new version of repo is available', file=sys.stderr)
    wrapper = Wrapper()
    try:
      rev = rp.bare_git.describe(rp.GetRevisionId())
    except GitError:
      rev = None
    _, new_rev = wrapper.check_repo_rev(rp.gitdir, rev, repo_verify=repo_verify)
    # See if we're held back due to missing signed tag.
    current_revid = rp.bare_git.rev_parse('HEAD')
    new_revid = rp.bare_git.rev_parse('--verify', new_rev)
    if current_revid != new_revid:
      # We want to switch to the new rev, but also not trash any uncommitted
      # changes.  This helps with local testing/hacking.
      # If a local change has been made, we will throw that away.
      # We also have to make sure this will switch to an older commit if that's
      # the latest tag in order to support release rollback.
      try:
        rp.work_git.reset('--keep', new_rev)
      except GitError as e:
        sys.exit(str(e))
      print('info: Restarting repo with latest version', file=sys.stderr)
      raise RepoChangedException(['--repo-upgraded'])
    else:
      print('warning: Skipped upgrade to unverified version', file=sys.stderr)
  else:
    if verbose:
      print('repo version %s is current' % rp.work_git.describe(HEAD),
            file=sys.stderr)
Beispiel #12
0
    def get_private_report(self,
                           username,
                           a_token,
                           report_name,
                           report_pass,
                           flag=''):

        wrapper = Wrapper(self.host, self.port)

        if not wrapper.check_connection():
            cquit(Status.DOWN, "Backend connection error!")

        Report = {
            'Name': report_name,
            'Password': report_pass,
            'Type': 'private'
        }

        result, errno = wrapper.view_report(username, a_token, Report)

        if errno == err.VIEW_REPORT_SUCCESS:
            if flag != '':
                if flag not in result['Data']:
                    cquit(Status.CORRUPT, "Flag in report is not valid!")

        else:
            if flag == '':
                cquit(Status.MUMBLE, "Could not get private report!")
            else:
                cquit(Status.CORRUPT, "Could not get private report!")
Beispiel #13
0
 def on_clicked(self):
     # capture parameters
     self.file_name = self.filename_comboBox.currentText()
     self.calc_year = self.period_comboBox.currentText()
     # create wrapper with current parameters
     self.wr = Wrapper(self.file_name, self.calc_year)
     self.wr.onclick_calculate()
Beispiel #14
0
 def __init__(self, *handlers, **kwargs):
     super(Container, self).__init__(*handlers, **kwargs)
     if "impl" not in kwargs:
         self.ssl = SSLConfig()
         self.global_handler = GlobalOverrides(kwargs.get("global_handler", self.global_handler))
         self.trigger = None
         self.container_id = str(generate_uuid())
         Wrapper.__setattr__(self, "subclass", self.__class__)
Beispiel #15
0
 def addWrapper(self, url):
     webView = Wrapper(self)
     webView.page().networkAccessManager().setCookieJar(self.cookiesjar)
     webView.page().networkAccessManager().setCache(self.diskCache)
     webView.load(QtCore.QUrl(url))
     webView.show()
     self.stackedWidget.addWidget(webView)
     self.stackedWidget.setCurrentWidget(webView)
Beispiel #16
0
class LogBookReport(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.file_name = ''  # Excel-File name
        self.calc_year = ''  # Period for calculate
        self.wr = None  # controller referenced object
        self.list_xlsx = [f for f in listdir(getcwd())
                          if '.xlsx' in f]  # future excel-filename list
        self.default_comboBox1 = 0  # default value for file_name_comboBox

        self.setWindowTitle("LogBook")
        self.setWindowIcon(QIcon('titleicon.png'))
        self.setFixedSize(300, 180)
        self.lab1 = QLabel('Choose File name')
        self.filename_comboBox = QComboBox()
        self.set_values_fname_combo()
        self.filename_comboBox.setCurrentIndex(self.default_comboBox1)

        self.lab2 = QLabel('Choose period')
        self.period_comboBox = QComboBox()
        self.set_values_period_combo()

        self.calculate_btn = QPushButton("Calculate")
        self.calculate_btn.clicked.connect(self.on_clicked)

        self.box = QVBoxLayout()
        self.box.addWidget(self.lab1)
        self.box.addWidget(self.filename_comboBox)
        self.box.addWidget(self.lab2)
        self.box.addWidget(self.period_comboBox)
        self.box.addWidget(self.calculate_btn)
        self.setLayout(self.box)
        self.show()

    # handler button click
    def on_clicked(self):
        # capture parameters
        self.file_name = self.filename_comboBox.currentText()
        self.calc_year = self.period_comboBox.currentText()
        # create wrapper with current parameters
        self.wr = Wrapper(self.file_name, self.calc_year)
        self.wr.onclick_calculate()

    # set excel-file names list
    def set_values_fname_combo(self):
        for i, f in enumerate(self.list_xlsx):
            self.filename_comboBox.addItem(f, i)
            if f == 'PILOT_LOG_532.xlsx':
                self.default_comboBox1 = i

    # set period list
    def set_values_period_combo(self):
        for i in range(2019, 2029):
            self.period_comboBox.addItem(str(i))
Beispiel #17
0
    def __init__(self, url):
        """ init """

        self.url = url
        self.token = ''

        Wrapper.disableWarnings()

        return
    def checkReportFormat(rformat):
        """ Check if chosen report format exists """

        formats = ('html', 'pdf')

        if rformat not in formats:
            Wrapper.error('Wrong report format: %s' % rformat)

        return
    def __init__(self, url):
        """ init """

        self.url = url
        self.token = ''

        Wrapper.disableWarnings()

        return
Beispiel #20
0
 def __init__(self, database, dir_path, debug=False):
     self._parser = Parser()
     self._wrapper = Wrapper()
     self._writer = Writer(database)
     self._sitemap_generator = SitemapGenerator(database)
     self._feeds_generator = FeedsGenerator(database)
     self._debug = debug
     self._dir_path = dir_path
     self._database = database
     self._file_path = ""
Beispiel #21
0
 def request(self, flow):
     if "Wrapper" in flow.request.headers and flow.request.headers[
             'Wrapper'] == '1':
         wrapper = Wrapper()
         result = wrapper.getData()
         # (token, sessid) = wrapper.getData()
         # flow.request.text = re.sub(r'_token=[a-zA-Z0-9]+', '_token=%s' % token, flow.request.text)
         # flow.request.cookies['roundcube_sessid'] = sessid
         del flow.request.headers['Wrapper']
         ctx.log.info('Wrapper No1 done!')
Beispiel #22
0
def baseline(env, agent, num_samples, n_episodes, horizon):
    wrapper = Wrapper(env, agent, log=True)
    total_r, trajectories = wrapper.eval_episodes(n_episodes, horizon=horizon)

    #trajectories = np.array(trajectories, dtype=int)
    #indices = np.random.choice(len(trajectories), num_samples)
    #samples = trajectories[indices]
    #return list(samples)
    samples = (sample(trajectories,num_samples))
    return samples
Beispiel #23
0
 def __init__(self, parent=None):
     super(ScudCloud, self).__init__(parent)
     self.setWindowTitle('ScudCloud')
     self.notifier = Notifier(self.APP_NAME, get_resource_path('scudcloud.png'))
     self.settings = QSettings(expanduser("~")+"/.scudcloud", QSettings.IniFormat)
     self.identifier = self.settings.value("Domain")
     if Unity is not None:
         self.launcher = Unity.LauncherEntry.get_for_desktop_id("scudcloud.desktop")
     else:
         self.launcher = DummyLauncher(self)
     self.leftPane = LeftPane(self)
     self.cookiesjar = PersistentCookieJar(self)
     webView = Wrapper(self)
     webView.page().networkAccessManager().setCookieJar(self.cookiesjar)
     self.stackedWidget = QtGui.QStackedWidget()
     self.stackedWidget.addWidget(webView)
     centralWidget = QtGui.QWidget(self)
     layout = QtGui.QHBoxLayout()
     layout.setContentsMargins(0, 0, 0, 0)
     layout.setSpacing(0)
     layout.addWidget(self.leftPane)
     layout.addWidget(self.stackedWidget)
     centralWidget.setLayout(layout)
     self.setCentralWidget(centralWidget)
     self.addMenu()
     self.tray = Systray(self)
     self.systray()
     self.installEventFilter(self)
     self.zoom()
     if self.identifier is None:
         webView.load(QtCore.QUrl(self.SIGNIN_URL))
     else:
         webView.load(QtCore.QUrl(self.domain()))
     webView.show()
Beispiel #24
0
 def __init__(self, parent = None, settings_path = ""):
     super(zcswebapp, self).__init__(parent)
     self.setWindowTitle('zcswebapp')
     self.settings_path = settings_path
     self.notifier = Notifier(Resources.APP_NAME, Resources.get_path('zcswebapp.png'))
     self.settings = QSettings(self.settings_path + '/zcswebapp.cfg', QSettings.IniFormat)
     self.identifier = self.settings.value("Domain")
     if Unity is not None:
         self.launcher = Unity.LauncherEntry.get_for_desktop_id("zcswebapp.desktop")
     else:
         self.launcher = DummyLauncher(self)
     self.webSettings()
     self.leftPane = LeftPane(self)
     webView = Wrapper(self)
     webView.page().networkAccessManager().setCookieJar(self.cookiesjar)
     self.stackedWidget = QtGui.QStackedWidget()
     self.stackedWidget.addWidget(webView)
     centralWidget = QtGui.QWidget(self)
     layout = QtGui.QHBoxLayout()
     layout.setContentsMargins(0, 0, 0, 0)
     layout.setSpacing(0)
     layout.addWidget(self.leftPane)
     layout.addWidget(self.stackedWidget)
     centralWidget.setLayout(layout)
     self.setCentralWidget(centralWidget)
     self.addMenu()
     self.tray = Systray(self)
     self.systray(zcswebapp.minimized)
     self.installEventFilter(self)
     if self.identifier is None:
         webView.load(QtCore.QUrl(Resources.SIGNIN_URL))
     else:
         webView.load(QtCore.QUrl(self.domain()))
     webView.show()
Beispiel #25
0
 def __init__(self, *handlers, **kwargs):
     super(Container, self).__init__(*handlers, **kwargs)
     if "impl" not in kwargs:
         try:
             self.ssl = SSLConfig()
         except SSLUnavailable:
             self.ssl = None
         self.global_handler = GlobalOverrides(kwargs.get('global_handler', self.global_handler))
         self.trigger = None
         self.container_id = str(generate_uuid())
         Wrapper.__setattr__(self, 'subclass', self.__class__)
    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
Beispiel #27
0
    def search_user(self, username, a_token):

        wrapper = Wrapper(self.host, self.port)

        if not wrapper.check_connection():
            cquit(Status.DOWN, "Backend connection error!")

        result, errno = wrapper.search_user(username, a_token, username[0:5])

        if errno != err.SEARCH_NAME_SUCCESS:
            cquit(Status.MUMBLE, "Backend: Could not find user!")
    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
Beispiel #29
0
 def addWrapper(self, url):
     webView = Wrapper(self)
     webView.page().networkAccessManager().setCookieJar(self.cookiesjar)
     webView.page().networkAccessManager().setCache(self.diskCache)
     webView.load(QtCore.QUrl(url))
     webView.show()
     self.stackedWidget.addWidget(webView)
     self.stackedWidget.setCurrentWidget(webView)
    def checkArgs(args):
        """ Check if required arguments are given """

        length = len(args)

        for a in args:
            if a not in sys.argv:
                length -= 1
                if length is 0:
                    Wrapper.error('Wrong usage. -H for help.')

        return
Beispiel #31
0
    def Execute(self, opt, args):
        git_require(MIN_GIT_VERSION_HARD, fail=True)
        if not git_require(MIN_GIT_VERSION_SOFT):
            print(
                'repo: warning: git-%s+ will soon be required; please upgrade your '
                'version of git to maintain support.' %
                ('.'.join(str(x) for x in MIN_GIT_VERSION_SOFT), ),
                file=sys.stderr)

        opt.quiet = opt.output_mode is False
        opt.verbose = opt.output_mode is True

        rp = self.manifest.repoProject

        # Handle new --repo-url requests.
        if opt.repo_url:
            remote = rp.GetRemote('origin')
            remote.url = opt.repo_url
            remote.Save()

        # Handle new --repo-rev requests.
        if opt.repo_rev:
            wrapper = Wrapper()
            remote_ref, rev = wrapper.check_repo_rev(
                rp.gitdir,
                opt.repo_rev,
                repo_verify=opt.repo_verify,
                quiet=opt.quiet)
            branch = rp.GetBranch('default')
            branch.merge = remote_ref
            rp.work_git.reset('--hard', rev)
            branch.Save()

        if opt.worktree:
            # Older versions of git supported worktree, but had dangerous gc bugs.
            git_require((2, 15, 0),
                        fail=True,
                        msg='git gc worktree corruption')

        self._SyncManifest(opt)
        self._LinkManifest(opt.manifest_name)

        if self.manifest.manifestProject.config.GetBoolean(
                'repo.superproject'):
            self._CloneSuperproject(opt)

        if os.isatty(0) and os.isatty(1) and not self.manifest.IsMirror:
            if opt.config_name or self._ShouldConfigureUser(opt):
                self._ConfigureUser(opt)
            self._ConfigureColor()

        self._DisplayResult(opt)
Beispiel #32
0
class Dashboard():

    table_name_files = "CustomerFiles"
    table_writers_files = "WriterFiles"
    table_name_messages = "MSSupport"

    def __init__(self):
        self.w = Wrapper()

    def get_new_files(self, uid):
        return self.w.select("*", self.table_writers_files, "where status=0 and id_order in (select id from Orders where id_customer={0});".format(uid))

    def get_new_messages(self, uid):
        return self.w.select("*", self.table_name_messages, " as ms left join MSSubject as sb on ms.id_subject = sb.id where ms.id_ms_status=1 and ms.id_customer={0}".format(uid))
Beispiel #33
0
    def loginCC(self):
        r = requests.get("http://localhost:3030/getCCChallenge?userID=" +
                         self.userName)
        challenge = (r.content)

        dealer = Wrapper()
        dealer.login()
        certChain = dealer.getCertificateChain()
        challengeSigned = dealer.sign(challenge.decode('hex'))
        dealer.logout()

        certChain = ';;:.:;;'.join(certChain)
        certChain = base64.urlsafe_b64encode(certChain)

        response = requests.get(
            "http://localhost:3030/authenticateCC?challengeSigned=" +
            challengeSigned + '&userID=' + self.userName + '&certChain=' +
            certChain)
        if response.content == '1':
            print 'User Authenticated!'
            self.getSessionKey()
            self.loginb = 1
        else:
            print 'User not Authenticated!'
            self.loginb = 0
    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 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 checkIniFile(ini):
        """ Check ini file configuration """

        sections = ini.sections()

        if not sections:
            Wrapper.error('Cannot read from ini file. Empty or wrong path?')

        check = ('nessus', 'mail', 'addressbook')

        for s in sections:
            if s not in check:
                Wrapper.warn('Missing or wrong section: [%s]' % s)

        return
Beispiel #37
0
class MisMatchFinder:
    def __init__(self):
        self.wrapper = Wrapper()

    def getGroups(self):
        self.groups = self.wrapper.getGroups()

    def getContracts(self):
        self.contracts = self.wrapper.getContractNames()

    def getProperties(self):
        for group in self.groups['groups']['items']:
            groupId = group['groupId']
            if 'contractIds' in group:
                for contractId in group['contractIds']:
                    location_result = self.wrapper.getProperties(
                        groupId, contractId)
                    if 'properties' in location_result:
                        for config_details in location_result['properties'][
                                'items']:
                            # Assign values to variables here for readability and will be used in rest of function.
                            propertyName = config_details['propertyName']
                            groupId = config_details['groupId']
                            contractId = config_details['contractId']
                            propertyId = config_details['propertyId']
                            productionVersion = config_details[
                                'productionVersion']
                            stgVersion = config_details['stagingVersion']
                            latestVersion = config_details['latestVersion']
                            firstVersion = 1
                            productId = None

                            property_details = self.wrapper.getPropertyVersions(
                                propertyId, groupId, contractId)
                            #print json.dumps(property_details)
                            productId = property_details['versions']['items'][
                                0]['productId'][4:]
                            origin_settings = Origin_Settings()
                            rules = self.wrapper.getConfigRuleTree(
                                propertyId, str(latestVersion), groupId,
                                contractId)
                            cpcodes = origin_settings.findOrigins(
                                rules, 'cpCode')
                            for cpcode in cpcodes:
                                if cpcode['products'] != None:
                                    if cpcode['products'].find(productId) < 0:
                                        print propertyName, productId, cpcode[
                                            'id'], cpcode['products']
Beispiel #38
0
class Admin(Users):
    """Admin Class
                    Methods:
                            adduser()
                            edituser()
                            deleteuser()
                            set_permission()
    """
    db_name = "users"

    def __init__(self):
        self.w = Wrapper()

    def __del__(self):
        pass

    def adduser(self, fields):
        """ Add user method insert data from user form in to db
        """
        return self.w.insert(fields, self.db_name)

    def edituser(self, fields, condition):
        """ Edit user method update user data
        """
        return self.w.update(fields, self.db_name, condition)

    def deleteuser(self, uid):
        """ Delete user method
            Dete user from db (change status to remove)
        """
        self.edituser({"id_status": "2"}, "where id={0}".format(uid))

    def set_permission(self, uname, role):
        """ Set user permission method
            change users permission
        """
        if role == 'admin':
            self.w.update(
                "id_role=1", self.db_name, "where login='******'".format(uname))
        if role == 'manager':
            self.w.update(
                "id_role=2", self.db_name, "where login='******'".format(uname))
        if role == 'waiter':
            self.w.update(
                "id_role=3", self.db_name, "where login='******'".format(uname))
        if role == 'cooker':
            self.w.update(
                "id_role=4", self.db_name, "where login='******'".format(uname))
Beispiel #39
0
def browser():
    driver = webdriver.Chrome(ChromeDriverManager().install())
    driver.maximize_window()
    driver.get("http://localhost/phpmyadmin/index.php")
    browser = Wrapper(driver)
    yield browser
    driver.quit()
Beispiel #40
0
  def Execute(self, opt, args):
    rp = self.manifest.repoProject
    rem = rp.GetRemote(rp.remote.name)
    branch = rp.GetBranch('default')

    # These might not be the same.  Report them both.
    src_ver = RepoSourceVersion()
    rp_ver = rp.bare_git.describe(HEAD)
    print('repo version %s' % rp_ver)
    print('       (from %s)' % rem.url)
    print('       (tracking %s)' % branch.merge)
    print('       (%s)' % rp.bare_git.log('-1', '--format=%cD', HEAD))

    if self.wrapper_path is not None:
      print('repo launcher version %s' % self.wrapper_version)
      print('       (from %s)' % self.wrapper_path)

      if src_ver != rp_ver:
        print('       (currently at %s)' % src_ver)

    print('repo User-Agent %s' % user_agent.repo)
    print('git %s' % git.version_tuple().full)
    print('git User-Agent %s' % user_agent.git)
    print('Python %s' % sys.version)
    uname = platform.uname()
    if sys.version_info.major < 3:
      # Python 3 returns a named tuple, but Python 2 is simpler.
      print(uname)
    else:
      print('OS %s %s (%s)' % (uname.system, uname.release, uname.version))
      print('CPU %s (%s)' %
            (uname.machine, uname.processor if uname.processor else 'unknown'))
    print('Bug reports:', Wrapper().BUG_URL)
Beispiel #41
0
def _CheckWrapperVersion(ver, repo_path):
  if not repo_path:
    repo_path = '~/bin/repo'

  if not ver:
    print('no --wrapper-version argument', file=sys.stderr)
    sys.exit(1)

  exp = Wrapper().VERSION
  ver = tuple(map(int, ver.split('.')))
  if len(ver) == 1:
    ver = (0, ver[0])

  exp_str = '.'.join(map(str, exp))
  if exp[0] > ver[0] or ver < (0, 4):
    print("""
!!! A new repo command (%5s) is available.    !!!
!!! You must upgrade before you can continue:   !!!

    cp %s %s
""" % (exp_str, WrapperPath(), repo_path), file=sys.stderr)
    sys.exit(1)

  if exp > ver:
    print("""
... A new repo command (%5s) is available.
... You should upgrade soon:

    cp %s %s
""" % (exp_str, WrapperPath(), repo_path), file=sys.stderr)
Beispiel #42
0
class Statuses(object):
	"""docstring for Statuses"""

	def __init__(self):
		self.wrapper = Wrapper()
	def get_all(self):
		return self.wrapper.select(["id", "status"], "statuses")
		
Beispiel #43
0
 def __getitem__(self, i):
   if i in self.cache:
     return self.cache[i]
   else:
     sc = Score()
     sc.parse(Wrapper.__getitem__(self, i))
     self.cache[i] = sc
     return sc
    def checkActions(action):
        """ Check if chosen action is valid. Print actions if '?' given. """

        if action == '?':
            Wrapper.msg('Available actions: \n')
            Wrapper.msg('report     - export and download nessus reports',
                    verbose=True)
            Wrapper.msg('summary    - create and download a summary report\n',
                    verbose=True)
            sys.exit(1337)

        if action not in ACTIONS:
            Wrapper.error('Please select a correct action')

        return
Beispiel #45
0
 def switchTo(self, url):
     index = -1
     for i in range(0, self.stackedWidget.count()):
         if self.stackedWidget.widget(i).url().toString().startswith(url):
             index = i
             break
     if index != -1:
         self.stackedWidget.setCurrentIndex(index)
     else:
         webView = Wrapper(self)
         webView.page().networkAccessManager().setCookieJar(self.cookiesjar)
         webView.load(QtCore.QUrl(url))
         webView.show()
         self.stackedWidget.addWidget(webView)
         self.stackedWidget.setCurrentWidget(webView)
     self.quicklist(self.current().listChannels())
Beispiel #46
0
 def switchTo(self, url):
     qUrl = QtCore.QUrl(url)
     index = -1
     for i in range(0, self.stackedWidget.count()):
         if self.stackedWidget.widget(i).url().toString().startswith(url):
             index = i
             break
     if index != -1:
         self.stackedWidget.setCurrentIndex(index)
     else:
         webView = Wrapper(self)
         webView.page().networkAccessManager().setCookieJar(self.cookiesjar)
         webView.load(qUrl)
         webView.show()
         self.stackedWidget.addWidget(webView)
         self.stackedWidget.setCurrentWidget(webView)
     self.quicklist(self.current().listChannels())
     self.enableMenus(self.current().isConnected())
     # Save the last used team as default
     self.settings.setValue("Domain", 'https://'+qUrl.host())
    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
Beispiel #48
0
 def __init__(self, *handlers, **kwargs):
     Wrapper.__init__(self, kwargs.get("impl", pn_reactor), pn_reactor_attachments)
     for h in handlers:
         self.handler.add(h)
Beispiel #49
0
 def __init__(self):
     Wrapper.__init__(self, sys.__stdin__)
Beispiel #50
0
 def __init__(self, impl):
     Wrapper.__init__(self, impl)
Beispiel #51
0
 def __init__(self, impl):
     Wrapper.__init__(self, impl, pn_task_attachments)
Beispiel #52
0
 def __init__(self):
     fd = sys.stdin.fileno()
     Wrapper.__init__(self, sys.__stdin__)
     self.fd = fd
Beispiel #53
0
from wrapper import Wrapper

ga = Wrapper()

ga.dump_mod()
    def end(self):
        """ Epilog """

        Wrapper.msg('Game Over')

        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