示例#1
0
    def ftp_upload(self, uploadlist=None, message=True):
        ftp1 = self.ftp_config
        msg = ""
        OK = True
        ftp = ftp_connect(ftp1["server"], ftp1["login"], ftp1["pass"])
        if ftp is None:
            msg += _("No FTP connexion")
            return
        if uploadlist is None:
            uploadlist = ["./idefix.json"]
        for file1 in uploadlist:
            ret = ftp_send(ftp, get_config_path(file1))
            if ret == True:
                msg += file1 + _(" sent\n")
            else:
                msg += ret
                OK = False
        ftp.close()

        if OK:
            title = "Upload OK"
        else:
            title = "ERRORS in upload"
        print(msg)

        if message:
            showwarning(title, msg, 1)
 def update_display(self, widget):
     self.arw['why_stack'].set_visible_child_name('page0')
     ftp1 = self.controller.ftp_config
     ftp = ftp_connect(ftp1["server"], ftp1["login"], ftp1["pass"])
     data1 = ftp_get(ftp, "result")
     self.arw["infos_label"].set_markup(data1)
     ftp.close()
示例#3
0
 def idefix2_test_ftp(self, *args):
     valid = ftp_connect(self.config['ftp']['ftp'],
                         self.config['ftp']['login'],
                         self.config['ftp']['password'])
     if not valid:
         alert(_("Could not conect to FTP"))
     else:
         showwarning(_("Test FTP"), _("FTP Connection Success"), 5)
示例#4
0
def test_ftp_login():

    # Подключаемся к FTP:
    ftp_connect()

    # Проходим аутентификацию:
    data_ftp_login = ftp.login(conf['user']['name'], conf['user']['password'])

    # Проверяем успешность авторизации:
    if 'Login' and 'successful' in data_ftp_login:
        print('Login successful')
    elif 'Login' and 'successful' not in data_ftp_login:
        assert False, 'Login incorrect. Verify user or password'
    else:
        assert False, 'Something wrong'

    # Завершаем подключение по FTP:
    ftp_client_finish()
    def get_infos(self,
                  command,
                  result="result",
                  progress=False,
                  decode_json=False):
        # get infos from Idefix. The process is :
        #  - write a command in the 'trigger' file
        #  - the command is processed by Idefix, and the result is written in the 'result' file
        #  - the 'result' file is read, and data returned.
        #  - if decode_json is set, then the data is first decoded
        #  - if progress is set, data is sent every second
        #  @spin : the spin object
        #  @ progress : a label object

        ftp1 = self.controller.ftp_config
        ftp = ftp_connect(ftp1["server"], ftp1["login"], ftp1["pass"])
        if not ftp:
            return False
        self.ftp = ftp

        command_f = io.BytesIO()
        ftp.storlines('STOR ' + result,
                      command_f)  # delete data in result file

        command_f.write(bytes(command, "utf-8"))
        command_f.seek(0)
        # send command
        ftp.storlines('STOR trigger', command_f)

        # wait until Idefix has finished the job
        time1 = time.time()
        for i in range(60):  # set absolute maximum to 60 seconds
            while time.time() < time1 + i:
                while Gtk.events_pending(
                ):  # necessary to have the spinner work
                    Gtk.main_iteration()
            if progress:
                data1 = ftp_get(ftp, result)
                progress.set_markup(me(data1))

            status = ftp_get(self.ftp, "trigger")
            if status == "ready":
                break

        data1 = ftp_get(ftp, result)
        ftp.close()

        if decode_json:
            data1 = json.loads(data1)

        return data1
 def save_file(self, widget):
     text_buffer = self.arw["editor_textview"].get_buffer()
     (start_iter, end_iter) = text_buffer.get_bounds()
     full_text = text_buffer.get_text(start_iter, end_iter, False)
     command_f = io.BytesIO()
     command_f.write(bytes(full_text, "utf-8"))  #.replace(b'\r\n', b'\n'))
     ftp1 = self.controller.ftp_config
     ftp = ftp_connect(ftp1["server"], ftp1["login"], ftp1["pass"])
     command_f.seek(0)
     ftp.storbinary('STOR buffer', command_f)
     command_f = io.BytesIO()
     command_f.write(
         bytes("linux cp /home/rock64/idefix/buffer " + self.edited_file,
               "utf-8"))
     command_f.seek(0)
     ftp.storbinary('STOR trigger', command_f)
示例#7
0
    def open_connexion_profile(self, configname=""):

        print("open connexion profile")
        self.mymac = None
        self.arw['loading_window'].show()
        while Gtk.events_pending():
            Gtk.main_iteration()
        # ftp connect
        ftp1 = self.ftp_config
        self.ftp = ftp_connect(ftp1["server"], ftp1["login"], ftp1["pass"],
                               self)
        self.arw['loading_window'].hide()

        if not self.ftp:
            # alert(_("Could not connect to %s (%s). \nVerify your cables or your configuration.") % (ftp1["server"], configname))
            return False
        else:
            # retrieve files by ftp
            data0 = ftp_get(self.ftp, "idefix.json", json=True)
            self.active_config_text = data0
            if data0:
                try:
                    self.config = json.loads(data0,
                                             object_pairs_hook=OrderedDict)
                    self.update()
                    self.update_gui()
                except:
                    # Try load a backup configuration
                    if askyesno(
                            _("Corrupted Configuration"),
                            _('Your configuration is corrupted. Search for backup?'
                              )):
                        return self.find_good_backup()
                    else:
                        self.config = OrderedDict()
                        self.load_defaults()
                self.ftp.close()
            else:
                self.load_defaults()

            if self.load_connection():
                return True
示例#8
0
    def import_network(self, data, auto_data=None):
        ftp1 = self.controller.ftp_config
        ftp = ftp_connect(ftp1["server"], ftp1["login"], ftp1["pass"])

        tmp_file = get_config_path('tmp_idefix2_conf.json')
        with open(tmp_file, 'w', newline="\n") as f:
            f.write(data)
        ftp_send(ftp, filepath=tmp_file, dest_name="idefix2_conf.json")
        os.unlink(tmp_file)

        if auto_data:
            # Optionally restore idefix_auto.conf if it was provided
            tmp_file = get_config_path('tmp_idefix_auto.conf')
            with open(tmp_file, 'w') as f:
                f.write(auto_data)
            ftp_send(ftp, filepath=tmp_file, dest_name="idefix_auto.conf")
            os.unlink(tmp_file)

        command_f = io.BytesIO()
        command_f.write(bytes("restore_config", "utf-8"))
        command_f.seek(0)
        # send command
        ftp.storlines('STOR trigger', command_f)
        ftp.close()
    def check_permissions(self, widget):
        """Run the permissions check after the check permission dialog has been completed"""
        self.refresh_users()

        # Show the selection dialog
        dialog = self.arw['permission_check_dialog']
        response = dialog.run()

        dialog.hide()

        if response != Gtk.ResponseType.OK:
            return

        model, selected_iter = self.arw['permission_check_user'].get_selection(
        ).get_selected()

        if not model or not selected_iter:
            showwarning(_("No User Selected"), _("Please select a user"))
            return

        user = model.get_value(selected_iter, 0)

        domain = self.arw['permission_check_domain'].get_text()

        if not domain:
            showwarning(_("No Domain Entered"),
                        _("Please enter a valid domain"))
            return

        self.arw['why_stack'].set_visible_child_name('why')

        # Retrieve the unbound json data from idefix
        ftp = ftp_connect(self.controller.ftp_config["server"],
                          self.controller.ftp_config["login"],
                          self.controller.ftp_config["pass"])
        if not ftp:
            return False

        data = ftp_get(ftp, 'unbound.json')
        if not data:
            showwarning(_("Could not get data"),
                        _("Could not retrieve permission data from idefix"))
            return False

        ftp.close()

        config = json.loads(data, object_pairs_hook=OrderedDict)

        self.arw['why_store'].clear()

        rule_info = self.is_allowed(user, domain, config)
        self.arw['why_info_label'].set_text(
            _("%s rules for %s") % (domain, user))

        for name, info in rule_info['rules'].items():

            rule_iter = self.arw['why_store'].append()
            self.arw['why_store'].set_value(rule_iter, WHY_COLUMN_NAME, name)

            # The domain is a list of matches to compare against the target domain
            # eg: ['com', 'microsoft', '*']  will match 'www.microsoft.com'
            # iterate through both target and rule domains looking for matches
            # if '*' is encountered then mark the rest of the domain as a pass
            # if a part of the domain doesn't match then mark the rest of the domain as fail

            rule_domain = iter(info.get('domain', []))
            domain_parts = []
            target_domain = reversed(domain.split('.'))

            while True:
                try:
                    source = rule_domain.__next__()
                except StopIteration:
                    source = ''

                try:
                    target = target_domain.__next__()
                except StopIteration:
                    break

                if source.lower() == target.lower():
                    domain_parts.append("<span foreground='green'>" + source +
                                        "</span>")
                    continue

                # Get the rest of the target
                parts = [target]
                while True:
                    try:
                        parts.append(target_domain.__next__())
                    except StopIteration:
                        break

                rest = '.'.join(reversed(parts))
                if source == '*':
                    # We match everything from here further down green
                    domain_parts.append("<span foreground='green'>" + rest +
                                        "</span>")
                else:
                    # This and everything below does not match and is red
                    domain_parts.append("<span foreground='red'>" + rest +
                                        "</span>")

            self.arw['why_store'].set_value(rule_iter, WHY_COLUMN_DOMAIN,
                                            '.'.join(reversed(domain_parts)))

            notes = ''
            if not info.get('user', True):
                notes += "<span foreground='red'>☹</span> "
            else:
                notes += "<span foreground='green'>☺</span> "

            if 'time_condition' in info:
                if not info.get('time_condition'):
                    notes += "<span foreground='red'>⏰</span> "
                else:
                    notes += "<span foreground='green'>⏰</span> "

            self.arw['why_store'].set_value(rule_iter,
                                            WHY_COLUMN_RULE_DISABLED,
                                            not info.get('enabled'))

            if not info.get('valid', True):
                self.arw['why_store'].set_value(rule_iter,
                                                WHY_COLUMN_RULE_INVALID, True)
                notes = info.get('reason')

            if 'action' in info:
                if info['action']:
                    self.arw['why_store'].set_value(rule_iter,
                                                    WHY_COLUMN_RULE_TYPE,
                                                    Gtk.STOCK_APPLY)
                else:
                    self.arw['why_store'].set_value(rule_iter,
                                                    WHY_COLUMN_RULE_TYPE,
                                                    Gtk.STOCK_CANCEL)
            else:
                self.arw['why_store'].set_value(rule_iter,
                                                WHY_COLUMN_RULE_TYPE,
                                                Gtk.STOCK_JUMP_TO)

            self.arw['why_store'].set_value(rule_iter, WHY_COLUMN_INFO, notes)
示例#10
0
    def run(self, source='local', offline=False, type=None):
        """ Run the restore dialog to select which files to restore. If type is specified then import those types
        without asking the user. Type can either be a string or an array. Source can be local for local files,
         ftp for ftp files or idefix for files on idefix"""

        if not offline:
            if not hasattr(self.controller, 'ftp') or not self.controller.ftp:
                alert(_(
                    "You cannot Restore a configuration without a connexion. \nIf you want to work offline, \nuse «Open Configuration on disk...» \nin the developper menu"))
                return

        zf = None

        if source == 'local':
            # Ask the user to select a file to restore

            dialog = Gtk.FileChooserDialog(
                _("Import Config"),
                self.arw['window1'],
                Gtk.FileChooserAction.OPEN,
                (_("Import"), Gtk.ResponseType.ACCEPT),
            )
            dialog.set_filter(self.file_filter)

            response = dialog.run()
            if response == Gtk.ResponseType.ACCEPT:
                self.configpath = dialog.get_filename()
                if self.configpath.lower().endswith('json'):
                    # Detect if we are importing permissions or network configuration
                    with open(self.configpath, 'rb') as f:
                        raw_data = f.read().decode('utf-8-sig')
                        data = json.loads(raw_data)
                        if 'users' in data or 'groups' in data:
                            self.import_permissions(raw_data)
                        elif 'eth0' in data or 'ftp' in data:
                            self.import_network(raw_data)
                    dialog.destroy()
                    return
                else:
                    try:
                        zf = zipfile.ZipFile(self.configpath)
                    except zipfile.BadZipFile:
                        alert(_("Zip file could not be read"))
                dialog.destroy()
            else:
                dialog.destroy()
                self.arw['restore_config_dialog'].hide()
                return

        elif source == 'ftp':
            # get the list of backups present on the ftp server
            # get Idefix ftp configuration

            if self.controller.idefix_module:
                ftp1 = json.loads(Information.get_infos(self, "ftp"))
                ftp = ftp_connect(ftp1["ftp"], ftp1["login"], ftp1["password"], self.controller)
            else:
                ftp1 = self.controller.ftp_config
                ftp = ftp_connect(ftp1["server"][0], ftp1["login"][0], ftp1["pass"][0])

            if ftp:
                ftp.cwd("backup")
                backup_list = ftp.nlst()
                backup_list.sort(reverse=True)
                self.arw["backups_list_store"].clear()
                for backup in backup_list:
                    self.arw["backups_list_store"].append([backup])
                response = self.arw["backup_restore"].run()
            else:
                alert(_("Could not get FTP connection"))
                response = Gtk.ResponseType.CANCEL

            if response == Gtk.ResponseType.OK:
                (model, node) = self.arw["backups_list_tree"].get_selection().get_selected()
                name = model.get_value(node, 0)
                backupfiledata = (ftp_get(ftp, name))
                backup_f = io.BytesIO()
                backup_f.write(backupfiledata)
                backup_f.seek(0)
                try:
                    zf = zipfile.ZipFile(backup_f)
                except zipfile.BadZipFile:
                    alert(_("Zip file could not be read"))
                self.arw["backup_restore"].hide()
            else:
                self.arw["backup_restore"].hide()
                self.arw['restore_config_dialog'].hide()
                return

        elif source == 'idefix':
            # get the list of backups present in Idefix

            x = Information.get_infos(self, "list_backups")
            backup_list = json.loads(x)
            backup_list.sort(reverse=True)

            self.arw["backups_list_store"].clear()

            for backup in backup_list:
                self.arw["backups_list_store"].append([backup])
            response = self.arw["backup_restore"].run()

            if response == Gtk.ResponseType.OK:
                (model, node) = self.arw["backups_list_tree"].get_selection().get_selected()
                name = model.get_value(node, 0)

                backupfiledata = (Information.get_infos(self, "get_backup " + name, result="result.zip"))
                backup_f = io.BytesIO()
                backup_f.write(backupfiledata)
                backup_f.seek(0)
                try:
                    zf = zipfile.ZipFile(backup_f)
                except zipfile.BadZipFile as e:
                    alert(_("Zip file could not be read"))
                self.arw["backup_restore"].hide()
            else:
                self.arw["backup_restore"].hide()
                self.arw['restore_config_dialog'].hide()
                return
        else:
            self.arw["backup_restore"].hide()
            self.arw['restore_config_dialog'].hide()
            return

        if not zf:
            self.arw['restore_config_dialog'].hide()
            return

        self.load_from_backup(zf, offline, type)