Exemple #1
0
    def create_project():
        '''Cria um projeto para ESP32 baseado no codigo demo blink'''

        d = Dialog(dialog="dialog")
        d.set_background_title(Menu.background_title)

        code, value = d.inputbox(text="Informe a frequencia do jtag em [KHz]")

        if code == d.OK:

            PROJECT.NAME = value

            code, path = d.dselect("./",
                                   title="Seleção do local do projeto",
                                   height=30,
                                   width=100)

            if code == d.OK:

                PROJECT.HOMEDIR = path

                copy_tree(ESP32.PROJECT_TEMPLATE, PROJECT.HOMEDIR)

                # renomeia o direotiro blink para o nome do projeto
                move_tree(PROJECT.HOMEDIR + '/blinck',
                          PROJECT.HOMEDIR + PROJECT.NAME)

                subprocess.call(
                    "sed -e '/PROJECT_NAME/D' '$filepath/$new_project_name/Makefile' > '/tmp/Makefile'"
                )
                subprocess.call(
                    "echo  'PROJECT_NAME := '$new_project_name >> '/tmp/Makefile'"
                )

                copy_file("/tmp/Makefile",
                          "%s/%s" % (PROJECT.HOMEDIR, PROJECT.NAME))
Exemple #2
0
class FormDialog:
    """
	Property that stores an object of type Dialog.
	"""
    d = None
    """
	Property that stores an object of type Utils.
	"""
    utils = None
    """
	Property that stores an object of type Elastic.
	"""
    elastic = None
    """
	Property that stores an object of type Logger.
	"""
    logger = None
    """
	Property that stores an object of type Telegram.
	"""
    telegram = None

    configuration = None
    """
	Constructor for the FormDialog class.

	Parameters:
	self -- An instantiated object of the FormDialog class.
	"""
    def __init__(self):
        self.d = Dialog(dialog="dialog")
        self.logger = Logger()
        self.utils = Utils(self)
        self.elastic = Elastic(self)
        self.telegram = Telegram(self)
        self.configuration = Configuration(self)
        self.d.set_background_title("SNAP-TOOL")

    """
	Method that generates the menu interface.

	Parameters:
	self -- An instantiated object of the FormDialogs class.
	text -- Text displayed on the interface.
	options -- List of options that make up the menu.
	title -- Title displayed on the interface.

	Return:
	tag_menu -- Chosen option.
	"""

    def getMenu(self, text, options, title):
        code_menu, tag_menu = self.d.menu(text=text,
                                          choices=options,
                                          title=title)
        if code_menu == self.d.OK:
            return tag_menu
        if code_menu == self.d.CANCEL:
            exit(0)

    """
	Method that generates the interface for entering decimal or floating type data.

	Parameters:
	self -- An instantiated object of the FormDialogs class.
	text -- Text displayed on the interface.
	initial_value -- Default value shown on the interface.

	Return:
	tag_inputbox -- Decimal or float value entered.
	"""

    def getDataNumberDecimal(self, text, initial_value):
        decimal_reg_exp = re_compile(r'^[1-9](\.[0-9]+)?$')
        while True:
            code_inputbox, tag_inputbox = self.d.inputbox(text=text,
                                                          height=10,
                                                          width=50,
                                                          init=initial_value)
            if code_inputbox == self.d.OK:
                if (not self.utils.validateRegularExpression(
                        decimal_reg_exp, tag_inputbox)):
                    self.d.msgbox(
                        text=
                        "\nInvalid data entered. Required value (decimal or float).",
                        height=8,
                        width=50,
                        title="Error Message")
                else:
                    return tag_inputbox
            elif code_inputbox == self.d.CANCEL:
                self.mainMenu()

    """
	Method that generates an interface to enter an IP address.

	Parameters:
	self -- An instantiated object of the FormDialogs class.
	text -- Text displayed on the interface.
	initial_value -- Default value shown on the interface.

	Return:
	tag_inputbox -- IP address entered.
	"""

    def getDataIP(self, text, initial_value):
        ip_reg_exp = re_compile(
            r'^(?:(?:[1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}(?:[1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$|^localhost$'
        )
        while True:
            code_inputbox, tag_inputbox = self.d.inputbox(text=text,
                                                          height=10,
                                                          width=50,
                                                          init=initial_value)
            if code_inputbox == self.d.OK:
                if (not self.utils.validateRegularExpression(
                        ip_reg_exp, tag_inputbox)):
                    self.d.msgbox(
                        text=
                        "\nInvalid data entered. Required value (IP address).",
                        height=8,
                        width=50,
                        title="Error Message")
                else:
                    return tag_inputbox
            elif code_inputbox == self.d.CANCEL:
                self.mainMenu()

    """
	Method that generates an interface to enter a port.

	Parameters:
	self -- An instantiated object of the FormDialogs class.
	text -- Text displayed on the interface.
	initial_value -- Default value shown on the interface.

	Return:
	tag_inputbox -- Port entered.
	"""

    def getDataPort(self, text, initial_value):
        port_reg_exp = re_compile(
            r'^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$'
        )
        while True:
            code_inputbox, tag_inputbox = self.d.inputbox(text=text,
                                                          height=10,
                                                          width=50,
                                                          init=initial_value)
            if code_inputbox == self.d.OK:
                if (not self.utils.validateRegularExpression(
                        port_reg_exp, tag_inputbox)):
                    self.d.msgbox(
                        text=
                        "\nInvalid data entered. Required value (0 - 65535).",
                        height=8,
                        width=50,
                        title="Error Message")
                else:
                    return tag_inputbox
            elif code_inputbox == self.d.CANCEL:
                self.mainMenu()

    """
	Method that generates an interface to enter text.

	Parameters:
	self -- An instantiated object of the FormDialogs class.
	text -- Text displayed on the interface.
	initial_value -- Default value shown on the interface.

	Return:
	tag_inputbox -- Text entered.
	"""

    def getDataInputText(self, text, initial_value):
        while True:
            code_inputbox, tag_inputbox = self.d.inputbox(text=text,
                                                          height=10,
                                                          width=50,
                                                          init=initial_value)
            if code_inputbox == self.d.OK:
                if tag_inputbox == "":
                    self.d.msgbox(
                        text=
                        "\nInvalid data entered. Required value (not empty).",
                        height=8,
                        width=50,
                        title="Error Message")
                else:
                    return tag_inputbox
            elif code_inputbox == self.d.CANCEL:
                self.mainMenu()

    """
	Method that generates an interface to enter a password.

	Parameters:
	self -- An instantiated object of the FormDialogs class.
	text -- Text displayed on the interface.
	initial_value -- Default value shown on the interface.

	Return:
	tag_passwordbox -- Password entered.
	"""

    def getDataPassword(self, text, initial_value):
        while True:
            code_passwordbox, tag_passwordbox = self.d.passwordbox(
                text=text,
                height=10,
                width=50,
                init=initial_value,
                insecure=True)
            if code_passwordbox == self.d.OK:
                if tag_passwordbox == "":
                    self.d.msgbox(
                        text=
                        "\nInvalid data entered. Required value (not empty).",
                        height=8,
                        width=50,
                        title="Error Message")
                else:
                    return tag_passwordbox
            elif code_passwordbox == self.d.CANCEL:
                self.mainMenu()

    """
	Method that generates a decision-making interface (yes / no).

	Parameters:
	self -- An instantiated object of the FormDialogs class.
	text -- Text displayed on the interface.
	title -- Title displayed on the interface.

	Return:
	tag_yesno -- Chosen option (yes or no).
	"""

    def getDataYesOrNo(self, text, title):
        tag_yesno = self.d.yesno(text=text, height=10, width=50, title=title)
        return tag_yesno

    """
	Method that generates an interface with several available options, and where only one of them can be chosen.

	Parameters:
	self -- An instantiated object of the FormDialogs class.
	text -- Text displayed on the interface.
	options -- List of options that make up the interface.
	title -- Title displayed on the interface.

	Return:
	tag_radiolist -- Chosen option.
	"""

    def getDataRadioList(self, text, options, title):
        while True:
            code_radiolist, tag_radiolist = self.d.radiolist(text=text,
                                                             width=65,
                                                             choices=options,
                                                             title=title)
            if code_radiolist == self.d.OK:
                if len(tag_radiolist) == 0:
                    self.d.msgbox(text="\nSelect at least one option.",
                                  height=7,
                                  width=50,
                                  title="Error Message")
                else:
                    return tag_radiolist
            elif code_radiolist == self.d.CANCEL:
                self.mainMenu()

    """
	Method that generates an interface with several available options, and where you can choose one or more of them.

	Parameters:
	self -- An instantiated object of the FormDialogs class.
	text -- Text displayed on the interface.
	options -- List of options that make up the interface.
	title -- Title displayed on the interface.

	Return:
	tag_checklist -- List with the chosen options.
	"""

    def getDataCheckList(self, text, options, title):
        while True:
            code_checklist, tag_checklist = self.d.checklist(text=text,
                                                             width=75,
                                                             choices=options,
                                                             title=title)
            if code_checklist == self.d.OK:
                if len(tag_checklist) == 0:
                    self.d.msgbox(text="\nSelect at least one option.",
                                  height=7,
                                  width=50,
                                  title="Error Message")
                else:
                    return tag_checklist
            elif code_checklist == self.d.CANCEL:
                self.mainMenu()

    """
	Method that generates an interface to select a file.

	Parameters:
	self -- An instantiated object of the FormDialogs class.
	initial_path -- Initial path in the interface.
	title -- Title displayed on the interface.
	extension_file -- Allowed file extension.

	Return:
	tag_fselect -- Path of the selected file.
	"""

    def getFile(self, initial_path, title, extension_file):
        while True:
            code_fselect, tag_fselect = self.d.fselect(filepath=initial_path,
                                                       height=8,
                                                       width=50,
                                                       title=title)
            if code_fselect == self.d.OK:
                if tag_fselect == "":
                    self.d.msgbox(text="\nSelect a file. Required value: " +
                                  extension_file + " file.",
                                  height=7,
                                  width=50,
                                  title="Error Message")
                else:
                    ext_file = Path(tag_fselect).suffix
                    if not ext_file == extension_file:
                        self.d.msgbox(
                            text="\nSelect a file. Required value: " +
                            extension_file + " file.",
                            height=7,
                            width=50,
                            title="Error Message")
                    else:
                        return tag_fselect
            elif code_fselect == self.d.CANCEL:
                self.mainMenu()

    """
	Method that generates an interface to select a directory.

	Parameters:
	self -- An instantiated object of the FormDialog class.
	initial_path -- Initial path in the interface.
	title -- Title displayed on the interface.

	Return:
	tag_dselect -- Selected directory.
	"""

    def getDirectory(self, initial_path, title):
        while True:
            code_dselect, tag_dselect = self.d.dselect(filepath=initial_path,
                                                       height=8,
                                                       width=50,
                                                       title=title)
            if code_dselect == self.d.OK:
                if tag_dselect == "":
                    self.d.msgbox(
                        text=
                        "\nSelect a directory. Required value (not empty).",
                        height=7,
                        width=50,
                        title="Error Message")
                else:
                    return tag_dselect
            elif code_dselect == self.d.CANCEL:
                self.mainMenu()

    """
	Method that generates an interface with scroll box.

	Parameters:
	self -- An instantiated object of the FormDialogs class.
	text -- Text displayed on the interface.
	title -- Title displayed on the interface.
	"""

    def getScrollBox(self, text, title):
        code_scrollbox = self.d.scrollbox(text=text,
                                          height=15,
                                          width=70,
                                          title=title)

    """
	Method that defines the action to be performed on the Snap-Tool configuration file (creation or modification).

	Parameters:
	self -- An instantiated object of the FormDialog class.
	"""

    def defineConfiguration(self):
        options_conf_false = [("Create", "Create the configuration file", 0)]

        options_conf_true = [("Modify", "Modify the configuration file", 0)]

        if not path.exists(self.configuration.conf_file):
            opt_conf_false = self.getDataRadioList("Select a option:",
                                                   options_conf_false,
                                                   "Configuration Options")
            if opt_conf_false == "Create":
                self.configuration.createConfiguration()
        else:
            opt_conf_true = self.getDataRadioList("Select a option:",
                                                  options_conf_true,
                                                  "Configuration Options")
            if opt_conf_true == "Modify":
                self.configuration.updateConfiguration()

    """
	Method that creates a repository of type FS in ElasticSearch.

	Parameters:
	self -- An instantiated object of the FormDialog class.

	Exceptions:
	KeyError -- A Python KeyError exception is what is raised when you try to access a key that isn’t in a dictionary (dict).
	"""

    def createRepository(self):
        try:
            if not path.exists(self.configuration.conf_file):
                self.d.msgbox(text="\nConfiguration file not found.",
                              height=7,
                              width=50,
                              title="Error Message")
            else:
                repository_name = self.getDataInputText(
                    "Enter the name to be assigned to the repository:",
                    "repository_name")
                path_repository = self.getDirectory("/etc/Snap-Tool",
                                                    "Repository path")
                compress_repository = self.getDataYesOrNo(
                    "\nDo you require metadata files to be stored compressed?",
                    "Repository compression")
                if compress_repository == "ok":
                    compress_repository = True
                else:
                    compress_repository = False
                snap_tool_conf = self.utils.readYamlFile(
                    self.configuration.conf_file, 'r')
                conn_es = self.elastic.getConnectionElastic()
                self.elastic.createRepositoryFS(conn_es, repository_name,
                                                path_repository,
                                                compress_repository)
                message_create_repository = self.telegram.getMessageCreateRepository(
                    repository_name, path_repository, compress_repository)
                self.telegram.sendTelegramAlert(
                    self.utils.decryptAES(
                        snap_tool_conf['telegram_chat_id']).decode('utf-8'),
                    self.utils.decryptAES(
                        snap_tool_conf['telegram_bot_token']).decode('utf-8'),
                    message_create_repository)
                self.logger.createSnapToolLog(
                    "Repository created: " + repository_name, 1)
                self.d.msgbox(text="\nRepository created: " + repository_name,
                              height=7,
                              width=50,
                              title="Notification Message")
                conn_es.transport.close()
            self.mainMenu()
        except KeyError as exception:
            self.logger.createSnapToolLog("Key Error: " + exception, 3)
            self.d.msgbox(
                text=
                "\nFailed to create snapshot. For more information, see the logs.",
                height=8,
                width=50,
                title="Error Message")
            self.mainMenu()

    """
	Method that removes one or more FS type repositories in ElasticSearch.

	Parameters:
	self -- An instantiated object of the FormDialog class.

	Exceptions:
	KeyError -- A Python KeyError exception is what is raised when you try to access a key that isn’t in a dictionary (dict).
	"""

    def deleteRepository(self):
        try:
            if not path.exists(self.configuration.conf_file):
                self.d.msgbox(text="\nConfiguration file not found.",
                              height=7,
                              width=50,
                              title="Error Message")
            else:
                conn_es = self.elastic.getConnectionElastic()
                list_aux_repositories = self.elastic.getAllRepositories(
                    conn_es)
                if len(list_aux_repositories) == 0:
                    self.d.msgbox(text="\nThere are no repositories created.",
                                  height=7,
                                  width=50,
                                  title="Notification Message")
                else:
                    snap_tool_conf = self.utils.readYamlFile(
                        self.configuration.conf_file, 'r')
                    list_all_repositories = self.utils.convertListToCheckOrRadioList(
                        list_aux_repositories, "Repository Name")
                    opt_repos = self.getDataCheckList(
                        "Select one or more options:", list_all_repositories,
                        "Repositories")
                    confirm_delete_repos = self.getDataYesOrNo(
                        "\nAre you sure to delete the following repository(s)?",
                        "Delete repositories")
                    if confirm_delete_repos == "ok":
                        message_to_display = "\nDeleted repositories:\n\n"
                        for repo_name in opt_repos:
                            self.elastic.deleteRepositoryFS(conn_es, repo_name)
                            message_to_display += "\n- " + repo_name
                            message_delete_repository = self.telegram.getMessageDeleteRepository(
                                repo_name)
                            self.telegram.sendTelegramAlert(
                                self.utils.decryptAES(
                                    snap_tool_conf['telegram_chat_id']).decode(
                                        'utf-8'),
                                self.utils.decryptAES(
                                    snap_tool_conf['telegram_bot_token']).
                                decode('utf-8'), message_delete_repository)
                            self.logger.createSnapToolLog(
                                "Deleted repository: " + repo_name, 2)
                        self.getScrollBox(message_to_display,
                                          "Deleted repositories")
                conn_es.transport.close()
            self.mainMenu()
        except KeyError as exception:
            self.logger.createSnapToolLog("Key Error: " + exception, 3)
            self.d.msgbox(
                text=
                "\nFailed to delete repository. For more information, see the logs.",
                height=8,
                width=50,
                title="Error Message")
            self.mainMenu()

    """
	Method that creates a snapshot of a particular index and allows the index to be deleted or not.

	Parameters:
	self -- An instantiated object of the FormDialog class.

	Exceptions:
	KeyError -- A Python KeyError exception is what is raised when you try to access a key that isn’t in a dictionary (dict). 
	"""

    def createSnapshot(self):
        try:
            if not path.exists(self.configuration.conf_file):
                self.d.msgbox(text="\nConfiguration file not found.",
                              height=7,
                              width=50,
                              title="Error Message")
            else:
                conn_es = self.elastic.getConnectionElastic()
                list_aux_indices = self.elastic.getIndices(conn_es)
                if len(list_aux_indices) == 0:
                    self.d.msgbox(text="\nThere are no indexes to back up.",
                                  height=7,
                                  width=50,
                                  title="Notification Message")
                else:
                    list_all_indices = self.utils.convertListToCheckOrRadioList(
                        list_aux_indices, "Index name")
                    opt_index = self.getDataRadioList("Select a option:",
                                                      list_all_indices,
                                                      "Indices")
                    list_aux_repositories = self.elastic.getAllRepositories(
                        conn_es)
                    if len(list_aux_repositories) == 0:
                        self.d.msgbox(text="\nThere are no repositories.",
                                      height=7,
                                      width=50,
                                      title="Notification Message")
                    else:
                        snap_tool_conf = self.utils.readYamlFile(
                            self.configuration.conf_file, 'r')
                        list_all_repositories = self.utils.convertListToCheckOrRadioList(
                            list_aux_repositories, "Repository name")
                        opt_repo = self.getDataRadioList(
                            "Select a option:", list_all_repositories,
                            "Repositories")
                        self.elastic.createSnapshot(conn_es, opt_repo,
                                                    opt_index)
                        message_creation_start = self.telegram.getMessageStartCreationSnapshot(
                            opt_index, opt_repo)
                        self.telegram.sendTelegramAlert(
                            self.utils.decryptAES(
                                snap_tool_conf['telegram_chat_id']).decode(
                                    'utf-8'),
                            self.utils.decryptAES(
                                snap_tool_conf['telegram_bot_token']).decode(
                                    'utf-8'), message_creation_start)
                        self.logger.createSnapToolLog(
                            "Snapshot creation has started: " + opt_index, 1)
                        while True:
                            status_snapshot = self.elastic.getStatusSnapshot(
                                conn_es, opt_repo, opt_index)
                            if status_snapshot == "SUCCESS":
                                break
                            sleep(60)
                        snapshot_info = self.elastic.getSnapshotInfo(
                            conn_es, opt_repo, opt_index)
                        self.logger.createSnapToolLog(
                            "Snapshot creation has finished: " + opt_index, 1)
                        message_creation_end = self.telegram.getMessageEndSnapshot(
                            opt_index, opt_repo,
                            snapshot_info['snapshots'][0]['start_time'],
                            snapshot_info['snapshots'][0]['end_time'])
                        self.telegram.sendTelegramAlert(
                            self.utils.decryptAES(
                                snap_tool_conf['telegram_chat_id']).decode(
                                    'utf-8'),
                            self.utils.decryptAES(
                                snap_tool_conf['telegram_bot_token']).decode(
                                    'utf-8'), message_creation_end)
                        self.d.msgbox(text="\nSnapshot created: " + opt_index,
                                      height=7,
                                      width=50,
                                      title="Notification Message")
                        if snap_tool_conf['is_delete_index'] == True:
                            self.elastic.deleteIndex(conn_es, opt_index)
                            if not conn_es.indices.exists(opt_index):
                                self.logger.createSnapToolLog(
                                    "Index removed: " + opt_index, 1)
                                message_delete_index = self.telegram.getMessageDeleteIndex(
                                    opt_index)
                                self.telegram.sendTelegramAlert(
                                    self.utils.decryptAES(
                                        snap_tool_conf['telegram_chat_id']).
                                    decode('utf-8'),
                                    self.utils.decryptAES(
                                        snap_tool_conf['telegram_bot_token']).
                                    decode('utf-8'), message_delete_index)
                                self.d.msgbox(text="\nIndex removed: " +
                                              opt_index,
                                              height=7,
                                              width=50,
                                              title="Notification Message")
                        else:
                            delete_index = self.getDataYesOrNo(
                                "\nDo you want to delete the index?\n\n- " +
                                opt_index, "Delete Index")
                            if delete_index == "ok":
                                self.elastic.deleteIndex(conn_es, opt_index)
                                if not conn_es.indices.exists(opt_index):
                                    self.logger.createSnapToolLog(
                                        "Index removed: " + opt_index, 1)
                                    message_delete_index = self.telegram.getMessageDeleteIndex(
                                        opt_index)
                                    self.telegram.sendTelegramAlert(
                                        self.utils.decryptAES(
                                            snap_tool_conf['telegram_chat_id']
                                        ).decode('utf-8'),
                                        self.utils.decryptAES(snap_tool_conf[
                                            'telegram_bot_token']).decode(
                                                'utf-8'), message_delete_index)
                                    self.d.msgbox(text="\nIndex removed: " +
                                                  opt_index,
                                                  height=7,
                                                  width=50,
                                                  title="Notification Message")
                conn_es.transport.close()
            self.mainMenu()
        except KeyError as exception:
            self.logger.createSnapToolLog("Key Error: " + exception, 3)
            self.d.msgbox(
                text=
                "\nFailed to create snapshot. For more information, see the logs.",
                height=8,
                width=50,
                title="Error Message")
            self.mainMenu()

    """
	Method that removes one or more snapshots from ElasticSearch.

	Parameters:
	self -- An instantiated object of the FormDialog class.

	Exceptions:
	KeyError -- A Python KeyError exception is what is raised when you try to access a key that isn’t in a dictionary (dict). 
	"""

    def deleteSnapshot(self):
        try:
            if not path.exists(self.configuration.conf_file):
                self.d.msgbox(text="\nConfiguration file not found.",
                              height=7,
                              width=50,
                              title="Error Message")
            else:
                conn_es = self.elastic.getConnectionElastic()
                list_aux_repositories = self.elastic.getAllRepositories(
                    conn_es)
                if len(list_aux_repositories) == 0:
                    self.d.msgbox(text="\nThere are no repositories created.",
                                  height=7,
                                  width=50,
                                  title="Notification Message")
                else:
                    list_all_repositories = self.utils.convertListToCheckOrRadioList(
                        list_aux_repositories, "Repository Name")
                    opt_repo = self.getDataRadioList("Select a option:",
                                                     list_all_repositories,
                                                     "Repositories")
                    list_aux_snapshots = self.elastic.getAllSnapshots(
                        conn_es, opt_repo)
                    if len(list_aux_snapshots) == 0:
                        self.d.msgbox(text="\nThere are no snapshots created.",
                                      height=7,
                                      width=50,
                                      title="Notification Message")
                    else:
                        snap_tool_conf = self.utils.readYamlFile(
                            self.configuration.conf_file, 'r')
                        list_all_snapshots = self.utils.convertListToCheckOrRadioList(
                            list_aux_snapshots, "Snapshot Name")
                        opt_snapshots = self.getDataCheckList(
                            "Select one or more options:", list_all_snapshots,
                            "Snapshots")
                        delete_snapshot = self.getDataYesOrNo(
                            "\nAre you sure to delete the selected snapshot(s)?",
                            "Delete Snapshot(s)")
                        if delete_snapshot == "ok":
                            for snapshot in opt_snapshots:
                                self.elastic.deleteSnapshotElastic(
                                    conn_es, opt_repo, snapshot)
                                message_delete_snapshot = self.telegram.getMessageDeleteSnapshot(
                                    snapshot, opt_repo)
                                self.telegram.sendTelegramAlert(
                                    self.utils.decryptAES(
                                        snap_tool_conf['telegram_chat_id']).
                                    decode('utf-8'),
                                    self.utils.decryptAES(
                                        snap_tool_conf['telegram_bot_token']).
                                    decode('utf-8'), message_delete_snapshot)
                            message = "\nThe following snapshots were removed:\n\n"
                            message += self.utils.convertListToString(
                                opt_snapshots)
                            self.getScrollBox(message, "Snapshot(s) deleted")
                conn_es.transport.close()
            self.mainMenu()
        except KeyError as exception:
            self.logger.createSnapToolLog("Key Error: " + exception, 3)
            self.d.msgbox(
                text=
                "\nFailed to delete snapshot(s). For more information, see the logs.",
                height=8,
                width=50,
                title="Error Message")
            self.mainMenu()

    """
	Method that restores a particular snapshot from ElasticSearch.

	Parameters:
	self -- An instantiated object of the FormDialog class.

	Exceptions:
	KeyError -- A Python KeyError exception is what is raised when you try to access a key that isn’t in a dictionary (dict).
	"""

    def restoreSnapshot(self):
        try:
            if not path.exists(self.configuration.conf_file):
                self.d.msgbox(text="\nConfiguration file not found.",
                              height=7,
                              width=50,
                              title="Error Message")
            else:
                conn_es = self.elastic.getConnectionElastic()
                list_aux_repositories = self.elastic.getAllRepositories(
                    conn_es)
                if len(list_aux_repositories) == 0:
                    self.d.msgbox(text="\nThere are no repositories created.",
                                  height=7,
                                  width=50,
                                  title="Notification Message")
                else:
                    list_all_repositories = self.utils.convertListToCheckOrRadioList(
                        list_aux_repositories, "Repository Name")
                    opt_repo = self.getDataRadioList("Select a option:",
                                                     list_all_repositories,
                                                     "Repositories")
                    list_aux_snapshots = self.elastic.getAllSnapshots(
                        conn_es, opt_repo)
                    if len(list_aux_snapshots) == 0:
                        self.d.msgbox(text="\nThere are no snapshots created.",
                                      height=7,
                                      width=50,
                                      title="Notification Message")
                    else:
                        snap_tool_conf = self.utils.readYamlFile(
                            self.configuration.conf_file, 'r')
                        list_all_snapshots = self.utils.convertListToCheckOrRadioList(
                            list_aux_snapshots, "Snapshot Name")
                        opt_snapshot = self.getDataRadioList(
                            "Select a option:", list_all_snapshots,
                            "Snapshots")
                        self.elastic.restoreSnapshot(conn_es, opt_repo,
                                                     opt_snapshot)
                        message_restore_snapshot = self.telegram.getMessageRestoreSnapshot(
                            opt_repo, opt_snapshot)
                        self.telegram.sendTelegramAlert(
                            self.utils.decryptAES(
                                snap_tool_conf['telegram_chat_id']).decode(
                                    'utf-8'),
                            self.utils.decryptAES(
                                snap_tool_conf['telegram_bot_token']).decode(
                                    'utf-8'), message_restore_snapshot)
                        self.logger.createSnapToolLog(
                            "Snapshot restored: " + opt_snapshot, 1)
                        self.d.msgbox(text="\nSnapshot restored: " +
                                      opt_snapshot + '.',
                                      height=7,
                                      width=50,
                                      title="Notification Message")
                conn_es.transport.close()
            self.mainMenu()
        except KeyError as exception:
            self.logger.createSnapToolLog("Key Error: " + exception, 3)
            self.d.msgbox(
                text=
                "\nFailed to restore snapshot. For more information, see the logs.",
                height=8,
                width=50,
                title="Error Message")
            self.mainMenu()

    """
	Method that mounts a snapshot as a searchable snapshot in ElasticSearch.

	Parameters:
	self -- An instantiated object of the FormDialog class.

	Exceptions:
	KeyError -- A Python KeyError exception is what is raised when you try to access a key that isn’t in a dictionary (dict).
	"""

    def mountSearchableSnapshot(self):
        try:
            if not path.exists(self.configuration.conf_file):
                self.d.msgbox(text="\nConfiguration file not found.",
                              height=7,
                              width=50,
                              title="Error Message")
            else:
                conn_es = self.elastic.getConnectionElastic()
                list_aux_repositories = self.elastic.getAllRepositories(
                    conn_es)
                if len(list_aux_repositories) == 0:
                    self.d.msgbox(text="\nThere are no repositories created.",
                                  height=7,
                                  width=50,
                                  title="Notification Message")
                else:
                    list_all_repositories = self.utils.convertListToCheckOrRadioList(
                        list_aux_repositories, "Repository Name")
                    opt_repo = self.getDataRadioList("Select a option:",
                                                     list_all_repositories,
                                                     "Repositories")
                    list_aux_snapshots = self.elastic.getAllSnapshots(
                        conn_es, opt_repo)
                    if len(list_aux_snapshots) == 0:
                        self.d.msgbox(text="\nThere are no snapshots created.",
                                      height=7,
                                      width=50,
                                      title="Notification Message")
                    else:
                        snap_tool_conf = self.utils.readYamlFile(
                            self.configuration.conf_file, 'r')
                        list_all_snapshots = self.utils.convertListToCheckOrRadioList(
                            list_aux_snapshots, "Snapshot Name")
                        opt_snapshot = self.getDataRadioList(
                            "Select a option:", list_all_snapshots,
                            "Snapshots")
                        self.elastic.mountSearchableSnapshot(
                            conn_es, opt_repo, opt_snapshot)
                        message_searchable_snapshot = self.telegram.getMessageSearchableSnapshot(
                            opt_repo, opt_snapshot)
                        self.telegram.sendTelegramAlert(
                            self.utils.decryptAES(
                                snap_tool_conf['telegram_chat_id']).decode(
                                    'utf-8'),
                            self.utils.decryptAES(
                                snap_tool_conf['telegram_bot_token']).decode(
                                    'utf-8'), message_searchable_snapshot)
                        self.logger.createSnapToolLog(
                            "Snapshot mounted as searchable snapshot: " +
                            opt_snapshot, 1)
                        self.d.msgbox(
                            text="\nSnapshot mounted as searchable snapshot: "
                            + opt_snapshot + '.',
                            height=8,
                            width=50,
                            title="Notification Message")
                conn_es.transport.close()
            self.mainMenu()
        except KeyError as exception:
            self.logger.createSnapToolLog("Key Error: " + exception, 3)
            self.d.msgbox(
                text=
                "\nFailed to mount snapshot as a searchable snapshot. For more information, see the logs.",
                height=8,
                width=50,
                title="Error Message")
            self.mainMenu()

    """
	Method that removes one or more indexes in ElasticSearch.

	Parameters:
	self -- An instantiated object of the FormDialog class.

	Exceptions:
	KeyError -- A Python KeyError exception is what is raised when you try to access a key that isn’t in a dictionary (dict).
	"""

    def deleteIndices(self):
        try:
            if not path.exists(self.configuration.conf_file):
                self.d.msgbox(text="\nConfiguration file not found.",
                              height=7,
                              width=50,
                              title="Error Message")
            else:
                conn_es = self.elastic.getConnectionElastic()
                list_aux_indices = self.elastic.getIndices(conn_es)
                if len(list_aux_indices) == 0:
                    self.d.msgbox(text="\nThere are no indexes to remove.",
                                  height=7,
                                  width=50,
                                  title="Notification Message")
                else:
                    list_all_indices = self.utils.convertListToCheckOrRadioList(
                        list_aux_indices, "Index name")
                    opt_indices = self.getDataCheckList(
                        "Select a option:", list_all_indices, "Indices")
                    confirm_delete_indices = self.getDataYesOrNo(
                        "\nAre you sure to delete the selected indices?",
                        "Delete indices")
                    if confirm_delete_indices == "ok":
                        snap_tool_conf = self.utils.readYamlFile(
                            self.configuration.conf_file, 'r')
                        message_to_display = "\nIndices removed:\n"
                        for index_name in opt_indices:
                            self.elastic.deleteIndex(conn_es, index_name)
                            message_to_display += "\n- " + index_name
                            self.logger.createSnapToolLog(
                                "Index removed: " + index_name, 2)
                            message_delete_indices = self.telegram.getMessageDeleteIndex(
                                index_name)
                            self.telegram.sendTelegramAlert(
                                self.utils.decryptAES(
                                    snap_tool_conf['telegram_chat_id']).decode(
                                        'utf-8'),
                                self.utils.decryptAES(
                                    snap_tool_conf['telegram_bot_token']).
                                decode('utf-8'), message_delete_indices)
                        self.getScrollBox(message_to_display,
                                          "Indices Removed")
                conn_es.transport.close()
            self.mainMenu()
        except KeyError as exception:
            self.logger.createSnapToolLog("Key Error: " + exception, 3)
            self.d.msgbox(
                text=
                "\nFailed to delete indices. For more information, see the logs.",
                height=8,
                width=50,
                title="Error Message")
            self.mainMenu()

    """
	Method that displays information related to the percentage of occupied disk space of the nodes of the elasticsearch cluster.

	Parameters:
	self -- An instantiated object of the FormDialog class.
	"""

    def showNodesDiskSpace(self):
        message_to_display = "Occupied space in nodes:\n\n"
        conn_es = self.elastic.getConnectionElastic()
        nodes_info = self.elastic.getNodesInformation(conn_es)
        for node in nodes_info:
            message_to_display += "- " + nodes_info[node]['name'] + '\n'
            total_disk = nodes_info[node]['fs']['total']['total_in_bytes']
            available_disk = nodes_info[node]['fs']['total'][
                'available_in_bytes']
            percentage = 100 - (available_disk * 100 / total_disk)
            message_to_display += "Percent occupied on disk: " + str(
                round(percentage, 2)) + "%\n\n"
        conn_es.transport.close()
        self.getScrollBox(message_to_display, "Node Information")
        self.mainMenu()

    """
	Method that displays a message on the screen with information about the application.

	Parameters:
	self -- An instantiated object of the FormDialog class.
	"""

    def getAbout(self):
        message = "\nCopyright@2021 Tekium. All rights reserved.\nSnap-Tool v3.1\nAuthor: Erick Rodriguez\nEmail: [email protected], [email protected]\n" + "License: GPLv3\n\nSnap-Tool is a tool that allows the management of snaphots in\nElasticSearch through a graphical interface."
        self.getScrollBox(message, "About")
        self.mainMenu()

    """
	Method that launches an action based on the option chosen in the main menu.

	Parameters:
	self -- An instantiated object of the FormDialog class.
	option -- Chosen option.
	"""

    def switchMmenu(self, option):
        if option == 1:
            self.defineConfiguration()
        elif option == 2:
            self.repositoryMenu()
        elif option == 3:
            self.snapshotMenu()
        elif option == 4:
            self.indicesMenu()
        elif option == 5:
            self.showNodesDiskSpace()
        elif option == 6:
            self.getAbout()
        elif option == 7:
            exit(0)

    """
	Method that launches an action based on the option chosen in the Repositories menu.

	Parameters:
	self -- An instantiated object of the FormDialog class.
	option -- Chosen option.
	"""

    def switchRmenu(self, option):
        if option == 1:
            self.createRepository()
        elif option == 2:
            self.deleteRepository()

    """
	Method that launches an action based on the option chosen in the Snapshots menu.

	Parameters:
	self -- An instantiated object of the FormDialog class.
	option -- Chosen option.
	"""

    def switchSmenu(self, option):
        if option == 1:
            self.createSnapshot()
        elif option == 2:
            self.deleteSnapshot()
        elif option == 3:
            self.restoreSnapshot()
        elif option == 4:
            self.mountSearchableSnapshot()

    """
	Method that launches an action based on the option chosen in the Indices menu.

	Parameters:
	self -- An instantiated object of the FormDialog class.
	option -- Chosen option.
	"""

    def switchImenu(self, option):
        if option == 1:
            self.deleteIndices()

    """
	Method that defines the menu on the actions to be carried out in the main menu.

	Parameters:
	self -- An instantiated object of the FormDialog class.
	"""

    def mainMenu(self):
        options_mm = [("1", "Snap-Tool Configuration"), ("2", "Repositories"),
                      ("3", "Snapshots"), ("4", "Indices"),
                      ("5", "Nodes information"), ("6", "About"),
                      ("7", "Exit")]

        option_mm = self.getMenu("Select a option:", options_mm, "Main Menu")
        self.switchMmenu(int(option_mm))

    """
	Method that defines the menu of actions that can be performed in relation to repositories.

	Parameters:
	self -- An instantiated object of the FormDialog class.
	"""

    def repositoryMenu(self):
        options_rm = [("1", "Create repository"), ("2", "Delete repositories")]

        option_rm = self.getMenu("Select a option:", options_rm,
                                 "Repositories menu")
        self.switchRmenu(int(option_rm))

    """
	Method that defines the menu of actions that can be performed in relation to snaphosts.

	Parameters:
	self -- An instantiated object of the FormDialog class.
	"""

    def snapshotMenu(self):
        options_sm = [("1", "Create Snapshot"), ("2", "Delete Snapshot(s)"),
                      ("3", "Restore snapshot"),
                      ("4", "Mount searchable snapshot")]

        option_sm = self.getMenu("Select a option:", options_sm,
                                 "Snapshots Menu")
        self.switchSmenu(int(option_sm))

    """
	Method that defines the menu of actions that can be performed in relation to indices.

	Parameters:
	self -- An instantiated object of the FormDialog class.
	"""

    def indicesMenu(self):
        options_im = [("1", "Delete indices")]

        option_im = self.getMenu("Select a option:", options_im,
                                 "Indices Menu")
        self.switchImenu(int(option_im))
Exemple #3
0
    parser.add_argument('-d', '--destination', help='path of directory to save videos to', default=os.path.curdir, metavar='')
    args = parser.parse_args()

    d = Dialog(dialog="dialog")
    d.set_background_title("Pytube-extension: Youtube playlist Dowload")

    processingMsg = u"처리중입니다."
    if args.playlisturl is '':
        code, url = d.inputbox(text=u"주소 입력", width=50)
        if code is d.CANCEL:
            print(u"사용자에의해 취소 되었습니다.")
            sys.exit()
    else:
        d.infobox(text=processingMsg)

    code, path = d.dselect(filepath=os.path.abspath(args.destination), width=50)
    if code == d.CANCEL:
        print(u"사용자에의해 취소 되었습니다.")
        sys.exit()

    """
    주소를 arguments로 직접 입력하였을시 빈 화면이 오래 보여지는 것 대신 처리중 문구를 보여 주기 위함.
    """
    d.infobox(text=processingMsg)
    pyt = Playlist(url if url else args.playlisturl, path)
    d.infobox(text=processingMsg)

    code, tags = d.checklist(u"다운받을 영상을 선택하세요.", choices=[(item.code, item.title, True) for item in pyt.items])
    
    pyt.checkDownload(tags=tags)
Exemple #4
0
                try:
                    x = float(answers[1][0])
                    y = float(answers[1][1])
                    z = float(answers[1][2])
                    pos = Position(x, y, z)
                    q = chargeUnit.multiplier()  # how much charge do you use?
                    par = (Particle(Position(x, y, z), q))
                    force = par.get_force()  # here's the error
                    d.msgbox(force.text())
                    del par  # keep memory usage low. Might be important for large projects/complex objects.
                    break
                except:
                    d.msgbox("All inputs must be numbers only.")

        elif tag == "Save":
            code, path = d.dselect("/", title="Choose a directory to save your file in:")
            if code != d.OK:
                break
            code, file = d.inputbox("Enter a file name:")
            if code != d.OK:
                break
            try:
                output_file = open(path+file, "w")
            except:
                print("Cannot open file.")
                break
            string = "<conditions>\n"
            for obj in objects:
                string += "    <particle>"
                string += "        <position>["+str(obj.position.x)+","+str(obj.position.y)+","+str(obj.position.z)+\
                          "]</position>"
Exemple #5
0
class STATES:
    #Current State
    current_state = 0

    def __init__(self):
        #State : 0
        locale.setlocale(locale.LC_ALL, '')
        self.text_port = "2222"
        self.text_host = "[email protected]"
        self.text_pass = "******"
        self.text_host_dir = "[email protected]:/home/pardus/Masaüstü/."
        self.path = "/home/" + pwd.getpwuid(os.getuid())[0] + "/Masaüstü/"
        self.d = Dialog(dialog="dialog")
        self.d.set_background_title("Yolla Gitsin Moruq")
        self.current_state = 1

    def state_info(self):
        #State : 01
        self.d.msgbox(
            "Hoş Geldiniz!\n\nLütfen dosyaların taşınmasını istediğiniz bilgisayarda openssh-server uygulamasının kurulu olduğundan emin olun.",
            width=40,
            height=12)
        self.current_state = 2

    def state_02(self):
        #STATE 2
        #Config Setting to Connect PC
        isDone, tag, text = self.d.inputmenu(
            "Bağlanılacak bilgisayarın bilgilerini giriniz",
            height=18,
            menu_height=16,
            choices=[("Port", self.text_port), ("Host", self.text_host),
                     ("Host_Direction", self.text_host_dir),
                     ("Password", self.text_pass)])
        if (isDone == 'renamed'):
            if (tag == 'Port'):
                self.text_port = text
            elif tag == "Password":
                self.text_pass = text
            elif tag == "Host":
                self.text_host = text
            elif tag == "Host_Direction":
                self.text_host_dir = text
        elif (isDone == 'accepted'):
            self.current_state += 1
        else:
            self.current_state -= 1

    def state_03(self):
        #State : 03
        code = self.d.yesno("SSH Key üretilsin mi?")
        if (code == self.d.OK):
            self.current_state = 4
        #7. State'e dallan
        else:
            self.current_state = 7

    def state_04(self):
        #State : 04
        #SSH-KEYGEN
        os.popen("rm -rf ~/.ssh")
        output = Popen(['ssh-keygen', '-t', 'rsa'], stdout=PIPE, stdin=PIPE)
        output.stdin.write("\n\n\n".encode())
        output.stdin.close()
        output.wait()
        self.d.infobox("SSH KEY'ler oluşturuldu.",
                       width=0,
                       height=0,
                       title="Başarılı")
        time.sleep(2)
        self.current_state = 5

    def state_05(self):
        #State : 05
        #ALERT : SSH-KEY Karşı Bilgisayar Kopyalanıcak
        self.d.infobox("Public KEY karşı pc'ye kopyalanıcak")
        time.sleep(1)
        self.current_state = 6

    def state_06(self):
        #State : 06
        #SSH-COPY-ID
        output2 = Popen([
            'sshpass -p "{}" ssh-copy-id -o StrictHostKeyChecking=no -p {} {} '
            .format(self.text_pass, self.text_port, self.text_host)
        ],
                        stdout=PIPE,
                        stdin=PIPE,
                        shell=True)
        output2.stdin.close()
        output2.wait()
        self.d.infobox("SSH KEY'ler aktarıldı.",
                       width=0,
                       height=0,
                       title="Başarılı")
        time.sleep(1)
        self.current_state = 8

    def state_07(self):
        #State : 07
        #SSH-KEYGEN ÜRETİLMEDEN çalıştırma
        self.d.infobox("SSH KEY üretilmeden devam ediliyor.",
                       width=40,
                       height=3)
        time.sleep(2)
        self.current_state = 8

    def state_08(self):
        #State : 08
        isDone, temp_path = self.d.dselect(self.path)
        if not (temp_path == ""):
            self.path = temp_path
        if isDone == 'ok':
            self.current_state = 9
        else:
            self.current_state = 2

    def state_09(self):
        #State : 09
        onlyfiles = [
            f for f in os.listdir(self.path)
            if os.path.isfile(os.path.join(self.path, f))
        ]
        onlyfiles_len = len(onlyfiles)
        info4files = []

        for i in range(onlyfiles_len):
            info4files.append((onlyfiles[i], "", False))

        code, send_files = self.d.checklist("Gönderilecek dosyaları seç",
                                            height=20,
                                            choices=info4files)
        if code == 'cancel':
            self.current_state = 8
        elif code == 'ok':
            send_files_len = len(send_files)
            if (send_files_len == 0):
                self.d.infobox("Dosya Seçilmedi")
                time.sleep(2)
            else:
                for i in range(send_files_len):
                    output3 = Popen([
                        'sshpass -p "{}" scp -P {} {} {}'.format(
                            self.text_pass, self.text_port,
                            os.path.join(self.path, send_files[i]),
                            self.text_host_dir)
                    ],
                                    stdin=PIPE,
                                    stdout=PIPE,
                                    shell=True)
                    output3.stdin.close()
                    out = output3.stdout.read().decode("utf-8")
                    self.d.infobox(text=out)
                    output3.wait()
            self.current_state = 10

    def state_repeat(self):
        #State : 10
        code = self.d.yesno("Dosya Yollamaya devam etmek ister misiniz?",
                            yes_label="Yes Baba",
                            no_label="No Baba")
        if (code == 'ok'):
            self.current_state = 8
        else:
            self.current_state = 11

    def state_final(self):
        #State : 11
        self.d.infobox("Çıkıyor Moruq")
        time.sleep(2)

    def state_login(self):
        #2
        code = self.d.yesno("Eski oturumlarla devam et",
                            yes_label="Yes Baba",
                            no_label="No Baba")
        if code == "ok":
            self.current_state = 21
        else:
            self.current_state = 22

    def state_login_read(self):
        # state 2.1 = 21
        try:
            _choices = []
            with open("Conf/conf.json", "r") as f:
                conf = json.load(f)
                for i in range(len(conf["user"])):
                    _str = "{}".format(conf["user"][i]["host"])
                    _choices.append((str(i), _str, False))
                code, tag = self.d.radiolist("kullanıcı ekranı",
                                             height=15,
                                             choices=_choices)
                if code == "ok":
                    self.text_port = conf["user"][int(tag)]["port"]
                    self.text_host = conf["user"][int(tag)]["host"]
                    self.text_pass = conf["user"][int(tag)]["pass"]
                    self.text_host_dir = conf["user"][int(tag)]["host_dir"]
                    self.current_state = 3
                else:
                    self.current_state = 2
        except (FileNotFoundError):
            self.d.infobox("Eski Oturum Bulunumadı!")
            time.sleep(2)
            self.current_state = 2

    def state_login_create(self):
        #State : 2.2 - 22
        isDone, tag, text = self.d.inputmenu(
            "Bağlanılacak bilgisayarın bilgilerini giriniz",
            height=18,
            menu_height=16,
            choices=[("Port", self.text_port), ("Host", self.text_host),
                     ("Host_Direction", self.text_host_dir),
                     ("Password", self.text_pass)])
        if (isDone == 'renamed'):
            if (tag == 'Port'):
                self.text_port = text
            elif tag == "Password":
                self.text_pass = text
            elif tag == "Host":
                self.text_host = text
            elif tag == "Host_Direction":
                self.text_host_dir = text
        elif (isDone == 'accepted'):
            conf = {}
            append_data = {
                "port": self.text_port,
                "host": self.text_host,
                "pass": self.text_pass,
                "host_dir": self.text_host_dir
            }
            isSameData = False
            try:
                #Eğer dosya oluşturulduysa
                with open("Conf/conf.json", "r") as f:
                    conf = json.load(f)
                    isSameData = CONTROLLER.isDictSame(append_data,
                                                       conf["user"])
            except:
                conf = {"user": []}
                os.mkdir("Conf")
            finally:
                if not (isSameData):
                    with open("Conf/conf.json", "w") as f:
                        conf["user"].append(append_data)
                        json.dump(conf, f, indent=4)
                        self.current_state = 3
                else:
                    self.d.infobox("Daha önceden kaydedilmiş içerik.")
                    time.sleep(2)
                    self.current_state = 2
        else:
            self.current_state = 2
Exemple #6
0
def get_info_via_dialog():
    global server
    global username
    global password
    global user  # chmod user
    global cred_file
    global mount_folder
    global create_mount_fld_as_sharename
    global fstab_loc

    from dialog import Dialog
    d = Dialog(dialog="dialog")

    button_names = {d.OK: "OK",
                    d.CANCEL: "Cancel",
                    d.HELP: "Help",
                    d.EXTRA: "Extra"}


    code, tag = d.mixedform("What sandwich toppings do you like?",
                             [("Server", 1, 1, "",1, 10, 20, 20, 0),
                              ("Username", 2, 1, "",2, 10, 20, 20, 0),
                              ("Password", 3, 1, "", 3, 10, 20, 20, 1)
                              ]
                )
    import pprint
    pprint.pprint(code)
    pprint.pprint(tag[1])

    if tag[0] != '' and tag[1] != '' and tag[2] != '':
        server = tag[0]
        username = tag[1]
        password = tag[2]
    else:
        sys.exit("Please specify all the input box's")

    code, tag = d.inputbox("Please enter the username who will have R/W access to the mounts")

    pprint.pprint(code)
    pprint.pprint(tag)

    #need to add checks for user
    user = tag

    code, tag = d.inputbox("Please enter the filename only, it will be edited to add the username and password\n and will be user in fstab or mount cmd")
    if tag != '':
        cred_file = tag


    code, tag = d.fselect('/etc/fstab')
    if tag != '':
        fstab_loc = tag

    import pathlib

    code, tag = d.dselect('/media')
    if tag != '' and pathlib.Path(tag).is_dir():
        mount_folder = tag
    else:
        sys.exit("Please select a folder to mount!")

    pprint.pprint(code)
    pprint.pprint(tag)