예제 #1
0
    def __init__(self, root, frame):
        self.root = root
        self.frame = Frame(frame)

        # Create the toolbar as a frame

        self.frame.columnconfigure(0, weight=1)
        self.frame.columnconfigure(1, weight=1)
        self.frame.rowconfigure(0, weight=1)
        self.frame.rowconfigure(1, weight=1)
        self.frame.grid_rowconfigure(1, minsize=70)

        self.img1 = Image.open("icons/open-folder.png").convert('RGBA')
        self.useImg1 = ImageTk.PhotoImage(self.img1)

        self.path = os.path.dirname(__file__)

        #self.style = ttk.Style()
        #self.style.configure('Treeview', rowheight=40)
        self.tree =  CheckboxTreeview(self.frame)

        #self.tree.pack(expand=YES, fill=BOTH)
        self.tree.heading("#0", text="Ficheiros")

        self.dir = self.tree.insert('', 'end', text=self.path, open=True)
        self.Subs(self.path, self.dir)


        self.tree.grid(row=0, column=0, columnspan=2, padx=4, pady=4, sticky=ALL)

        Button(self.frame, image=self.useImg1, width=70, height=70, command=self.browse_button).grid(row=2, column=1, padx=4, pady=4, sticky=E)

        self.frame.pack(side=TOP, fill=BOTH)
예제 #2
0
    def __init__(self, parent):
        """
            parent: the tkinter parent view to use for this window construction.
        """
        self.parent = parent
        self.app = tk.Toplevel(parent)
        self.app.title("Scripts Manager")
        self.app.resizable(True, True)
        self.rvalue = None
        appFrame = ttk.Frame(self.app)
         #PANED PART
        self.paned = tk.PanedWindow(appFrame, height=300)
        #RIGHT PANE : TAble
        self.viewframe = ttk.Frame(self.paned)
        self.file_tree = CheckboxTreeview(self.viewframe)
        self.file_tree['columns'] = ('name', 'category')
        self.file_tree.heading('#0', text='Name')
        self.file_tree.column("#0", stretch=tk.YES, minwidth=300, width=300)
        self.file_tree.heading('#1', text='Category')
        self.file_tree.column("#1", stretch=tk.YES, minwidth=300, width=300)
        self.file_tree.pack(fill=tk.BOTH, expand=True)
        btn_pane = ttk.Frame(self.viewframe)
        self.execute_icone = tk.PhotoImage(file = Utils.getIcon("execute.png"))
        btn_execute = ttk.Button(btn_pane, text="Execute", image=self.execute_icone, command=self.executedSelectedScripts, tooltip="Execute all selected scripts", style="Toolbutton")        
        btn_execute.pack(side=tk.RIGHT, padx=3, pady=5)
        self.open_folder_icone = tk.PhotoImage(file = Utils.getIcon("folder.png"))
        btn_openPathForUser = ttk.Button(btn_pane, text="Execute", image=self.open_folder_icone, command=self.openPathForUser, tooltip="Open scripts folder", style="Toolbutton")        
        btn_openPathForUser.pack(side=tk.RIGHT, padx=3, pady=5)
        
        btn_pane.pack(fill=tk.X, side=tk.BOTTOM, anchor=tk.E)
        #LEFT PANE : Treeview
        self.frameTw = ttk.Frame(self.paned)
        self.treevw = ttk.Treeview(self.frameTw)
        self.treevw.pack()
        scbVSel = ttk.Scrollbar(self.frameTw,
                                orient=tk.VERTICAL,
                                command=self.treevw.yview)
        self.treevw.configure(yscrollcommand=scbVSel.set)
        self.treevw.grid(row=0, column=0, sticky=tk.NSEW)
        scbVSel.grid(row=0, column=1, sticky=tk.NS)
        self.treevw.grid(row=0, column=0, sticky=tk.NSEW)
        scbVSel.grid(row=0, column=1, sticky=tk.NS)
        self.paned.add(self.frameTw)
        self.paned.add(self.viewframe)
        self.paned.pack(fill=tk.BOTH, expand=1)
        self.frameTw.rowconfigure(0, weight=1) # Weight 1 sur un layout grid, sans ça le composant ne changera pas de taille en cas de resize
        self.frameTw.columnconfigure(0, weight=1) # Weight 1 sur un layout grid, sans ça le composant ne changera pas de taille en cas de resize

        appFrame.pack(fill=tk.BOTH, ipady=10, ipadx=10, expand=True)

        self.treevw.bind("<<TreeviewSelect>>", self.onTreeviewSelect)
        try:
            self.app.wait_visibility()
            self.app.focus_force()
            self.app.lift()
        except tk.TclError:
            pass
        self.refreshUI()
예제 #3
0
 def __init__(self, master, client, database, strategy_frame, **kwargs):
     """
     :param master: master widget
     :param client: network.strategy.client.StrategyClient
     :param database: results.strategies.StrategyDataBase
     :param strategy_frame: frames.strategy.StrategyFrame
     :param kwargs: SnapToplevel keyword arguments
     """
     resizable = kwargs.pop("resizable", False)
     self._client = client
     self._database = database
     self._frame = strategy_frame
     Parent.__init__(self, master, **kwargs)
     self.wm_title("GSF Parser: Strategy Sharing")
     self.wm_resizable(resizable, resizable)
     # Configure the Treeview
     self.tree = CheckboxTreeview(master=self, height=16)
     self.tree.column("#0", width=200)
     self.tree.heading("#0", text="Strategy")
     self.tree.config(show=("headings", "tree"))
     self.scroll_bar = ttk.Scrollbar(self, orient=tk.VERTICAL, command=self.tree.yview)
     self.tree.config(yscrollcommand=self.scroll_bar.set)
     self.update_strategy_tree()
     self.share_button = ttk.Button(self, text="Share Strategies", command=self.share_strategies)
     self.grid_widgets()
예제 #4
0
class LeftPanel:
    def __init__(self, root, frame):
        self.root = root
        self.frame = Frame(frame)

        # Create the toolbar as a frame

        self.frame.columnconfigure(0, weight=1)
        self.frame.columnconfigure(1, weight=1)
        self.frame.rowconfigure(0, weight=1)
        self.frame.rowconfigure(1, weight=1)
        self.frame.grid_rowconfigure(1, minsize=70)

        self.img1 = Image.open("icons/open-folder.png").convert('RGBA')
        self.useImg1 = ImageTk.PhotoImage(self.img1)

        self.path = os.path.dirname(__file__)

        #self.style = ttk.Style()
        #self.style.configure('Treeview', rowheight=40)
        self.tree =  CheckboxTreeview(self.frame)

        #self.tree.pack(expand=YES, fill=BOTH)
        self.tree.heading("#0", text="Ficheiros")

        self.dir = self.tree.insert('', 'end', text=self.path, open=True)
        self.Subs(self.path, self.dir)


        self.tree.grid(row=0, column=0, columnspan=2, padx=4, pady=4, sticky=ALL)

        Button(self.frame, image=self.useImg1, width=70, height=70, command=self.browse_button).grid(row=2, column=1, padx=4, pady=4, sticky=E)

        self.frame.pack(side=TOP, fill=BOTH)

    def Subs(self, path, parent):
        for p in os.listdir(path):
            abspath = os.path.join(path, p)
            parent_element = self.tree.insert(parent, 'end', text=p, open=True)
            if os.path.isdir(abspath):
                self.Subs(abspath, parent_element)

    def browse_button(self):
        self.path = tkFileDialog.askdirectory()


    def set_dir(self):
        sourcePath = str(self.path)
        os.chdir(sourcePath)
    def generate_tree(self):
        root = tk.Tk()
        tree = CheckboxTreeview(root)
        #root.withdraw()

        visited = {ID: False for ID in self.id_to_name}
        for parent in self.dict:
            if visited[parent] == False:
                visited[parent] = True
                tree.insert("",
                            "end",
                            parent,
                            text=self.get_name_from_id(parent))
                self.generate_tree_dfs(parent, visited, tree)

        def callback():
            print(tree.get_checked())

        expanded = False
        btn_text = tk.StringVar()

        def expand_collapse(expanded):
            if expanded == False:
                expanded = True
                tree.expand_all()
                btn_text.set("Collapse All")
            else:
                expanded = False
                tree.collapse_all()
                btn_text.set("Expand All")

        submit = tk.Button(root, text="Submit", command=callback)
        exp_col_b = tk.Button(root,
                              textvariable=btn_text,
                              command=expand_collapse(expanded))

        root.geometry('500x500')
        #root.resizeable()
        exp_col_b.pack()
        tree.pack(fill=tk.BOTH)
        submit.pack()

        root.mainloop()
예제 #6
0
class StrategyShareToplevel(Parent):
    """
    Toplevel to display a list of strategy with checkboxes to allow
    selecting which should be shared.
    """
    def __init__(self, master, client, database, strategy_frame, **kwargs):
        """
        :param master: master widget
        :param client: network.strategy.client.StrategyClient
        :param database: results.strategies.StrategyDataBase
        :param strategy_frame: frames.strategy.StrategyFrame
        :param kwargs: SnapToplevel keyword arguments
        """
        resizable = kwargs.pop("resizable", False)
        self._client = client
        self._database = database
        self._frame = strategy_frame
        Parent.__init__(self, master, **kwargs)
        self.wm_title("GSF Parser: Strategy Sharing")
        self.wm_resizable(resizable, resizable)
        # Configure the Treeview
        self.tree = CheckboxTreeview(master=self, height=16)
        self.tree.column("#0", width=200)
        self.tree.heading("#0", text="Strategy")
        self.tree.config(show=("headings", "tree"))
        self.scroll_bar = ttk.Scrollbar(self, orient=tk.VERTICAL, command=self.tree.yview)
        self.tree.config(yscrollcommand=self.scroll_bar.set)
        self.update_strategy_tree()
        self.share_button = ttk.Button(self, text="Share Strategies", command=self.share_strategies)
        self.grid_widgets()

    def grid_widgets(self):
        self.tree.grid(row=1, column=1, sticky="nswe", padx=5, pady=5)
        self.scroll_bar.grid(row=1, column=2, sticky="ns", padx=(0, 5), pady=5)
        self.share_button.grid(row=2, column=1, columnspan=2, sticky="nswe", padx=5, pady=(0, 5))

    def share_strategies(self):
        for strategy in self.strategies_to_share:
            self._client.send_strategy(strategy)
        messagebox.showinfo("Info", "Selected Strategies sent.")

    def update_strategy_tree(self):
        self.tree.delete(*self.tree.get_children(""))
        for strategy in sorted(self._database.keys()):
            self.tree.insert("", tk.END, iid=strategy, text=strategy)

    @property
    def strategies_to_share(self):
        for strategy in self.tree.get_checked():
            yield self._database[strategy]
예제 #7
0
from ttkwidgets import CheckboxTreeview
import tkinter as tk
import tkinter.ttk as ttk

root = tk.Tk()
root.geometry('600x600')
root.title("Checkbox example")

f1 = tk.Frame(root, width=595, height=595, background='blue', bd=1)
f1.grid(row=0, column=0)
checkingFrame = tk.Frame(f1, width=590, height=590, background='yellow', bd=1)
checkingFrame.grid(row=0, column=0, padx=5, pady=5)
canvas_tree = tk.Canvas(checkingFrame, bg='white')
canvas_tree.grid(row=0, column=0)

main_tree = CheckboxTreeview(canvas_tree, show='tree')
main_tree.column("#0", width=500, minwidth=600, stretch=True)
main_tree.configure(height=10)

main_tree.insert("", "end", "1", text="1" + '2')
main_tree.insert("1", "end", "11", text="11")
main_tree.insert("1",
                 "end",
                 "12",
                 text="Anantha" + "kumar" + 'Kondra' + 'Anantha Kumar Kondra')
main_tree.insert("11",
                 "end",
                 "111",
                 text="Anantha" + "kumar" + 'Kondra' + 'Anantha Kumar Kondra')
main_tree.insert("",
                 "end",
예제 #8
0
from ttkwidgets import CheckboxTreeview
import tkinter as tk
import tkinter.ttk as ttk

root = tk.Tk()
root.geometry('500x500')
root.title("Checkbox example")

f1 = tk.Frame(root, width=490, height=490)
f1.grid()

can = tk.Canvas(f1, width=500)
tree = CheckboxTreeview(can, show='tree')
tree.column('#0', minwidth=350, stretch=True, width=300)
tree.insert("", "end", "1", text="1" + '2')
tree.insert("1", "end", "11", text="11")
tree.insert("1",
            "end",
            "12",
            text="Anantha" + "kumar" + 'Kondra' + 'Anantha Kumar Kondra')
tree.insert("11",
            "end",
            "111",
            text="Anantha" + "kumar" + 'Kondra' + 'Anantha Kumar Kondra')
tree.insert("",
            "end",
            "2",
            text="Anantha" + "kumar" + 'Kondra' + 'Anantha Kumar Kondra')
tree.grid()

xscrol = ttk.Scrollbar(can, orient=tk.HORIZONTAL, command=tree.xview)
예제 #9
0
class ScriptManager:
    """
    Open the scripts window manager
    """
    folder_icon = None
    def __init__(self, parent):
        """
            parent: the tkinter parent view to use for this window construction.
        """
        self.parent = parent
        self.app = tk.Toplevel(parent)
        self.app.title("Scripts Manager")
        self.app.resizable(True, True)
        self.rvalue = None
        appFrame = ttk.Frame(self.app)
         #PANED PART
        self.paned = tk.PanedWindow(appFrame, height=300)
        #RIGHT PANE : TAble
        self.viewframe = ttk.Frame(self.paned)
        self.file_tree = CheckboxTreeview(self.viewframe)
        self.file_tree['columns'] = ('name', 'category')
        self.file_tree.heading('#0', text='Name')
        self.file_tree.column("#0", stretch=tk.YES, minwidth=300, width=300)
        self.file_tree.heading('#1', text='Category')
        self.file_tree.column("#1", stretch=tk.YES, minwidth=300, width=300)
        self.file_tree.pack(fill=tk.BOTH, expand=True)
        btn_pane = ttk.Frame(self.viewframe)
        self.execute_icone = tk.PhotoImage(file = Utils.getIcon("execute.png"))
        btn_execute = ttk.Button(btn_pane, text="Execute", image=self.execute_icone, command=self.executedSelectedScripts, tooltip="Execute all selected scripts", style="Toolbutton")        
        btn_execute.pack(side=tk.RIGHT, padx=3, pady=5)
        self.open_folder_icone = tk.PhotoImage(file = Utils.getIcon("folder.png"))
        btn_openPathForUser = ttk.Button(btn_pane, text="Execute", image=self.open_folder_icone, command=self.openPathForUser, tooltip="Open scripts folder", style="Toolbutton")        
        btn_openPathForUser.pack(side=tk.RIGHT, padx=3, pady=5)
        
        btn_pane.pack(fill=tk.X, side=tk.BOTTOM, anchor=tk.E)
        #LEFT PANE : Treeview
        self.frameTw = ttk.Frame(self.paned)
        self.treevw = ttk.Treeview(self.frameTw)
        self.treevw.pack()
        scbVSel = ttk.Scrollbar(self.frameTw,
                                orient=tk.VERTICAL,
                                command=self.treevw.yview)
        self.treevw.configure(yscrollcommand=scbVSel.set)
        self.treevw.grid(row=0, column=0, sticky=tk.NSEW)
        scbVSel.grid(row=0, column=1, sticky=tk.NS)
        self.treevw.grid(row=0, column=0, sticky=tk.NSEW)
        scbVSel.grid(row=0, column=1, sticky=tk.NS)
        self.paned.add(self.frameTw)
        self.paned.add(self.viewframe)
        self.paned.pack(fill=tk.BOTH, expand=1)
        self.frameTw.rowconfigure(0, weight=1) # Weight 1 sur un layout grid, sans ça le composant ne changera pas de taille en cas de resize
        self.frameTw.columnconfigure(0, weight=1) # Weight 1 sur un layout grid, sans ça le composant ne changera pas de taille en cas de resize

        appFrame.pack(fill=tk.BOTH, ipady=10, ipadx=10, expand=True)

        self.treevw.bind("<<TreeviewSelect>>", self.onTreeviewSelect)
        try:
            self.app.wait_visibility()
            self.app.focus_force()
            self.app.lift()
        except tk.TclError:
            pass
        self.refreshUI()

    def refreshUI(self):
        for widget in self.treevw.winfo_children():
            widget.destroy()
        script_dir = self.getScriptsDir()
        if self.__class__.folder_icon is None:
            self.__class__.folder_icon = ImageTk.PhotoImage(Image.open(Utils.getIcon("folder.png")))
        parent = self.treevw.insert("", "end", " ", text="Scripts", image=self.__class__.folder_icon, open=True)
        self.treevw.focus(parent)
        self.treevw.selection_set(parent)
        for root, subFolders, files in os.walk(script_dir):
            root_name = root.replace(script_dir, "")
            for folder in subFolders:
                if folder.startswith("__") or folder.endswith("__"):
                    continue
                folder_iid = os.path.join(root_name, folder)
                parent_node = parent if root_name == "" else root_name
                self.treevw.insert(parent_node, "end", folder_iid, text=folder, image=self.__class__.folder_icon)
        self.openScriptFolderView()
        
    def getScriptsDir(self):
        return os.path.join(Utils.getMainDir(), "scripts/")

    def onTreeviewSelect(self, _event=None):
        
        selec = self.treevw.selection()
        if len(selec) == 0:
            return None
        item = selec[0]
        self.openScriptFolderView(str(item))

    def openScriptFolderView(self, script_folder=""):
        full_script_path = os.path.join(self.getScriptsDir(), script_folder.strip())
        script_shown = set()
        self.file_tree.delete(*self.file_tree.get_children())

        for root, _, files in os.walk(full_script_path):
            for file in files:
                filepath = root + '/' + file
                if file.endswith(".py"):
                    script_shown.add(filepath)
        scripts_list = sorted(script_shown)
        script_dir = self.getScriptsDir()
        for script in scripts_list:
            scriptName = os.path.basename(script)
            category_name = os.path.dirname(script.replace(script_dir, ""))
            self.file_tree.insert("", "end", script, text=scriptName, values=(category_name))
        

    def executedSelectedScripts(self):
        for selected in self.file_tree.get_checked():
            self.executeScript(selected)

    def executeScript(self, script_path):
        script_dir = self.getScriptsDir()
        category_name = os.path.dirname(script_path.replace(script_dir, ""))
        script_name = ".".join(os.path.splitext(os.path.basename(script_path))[:-1])
        module = os.path.join("pollenisatorgui/scripts/",category_name, script_name).replace("/", '.')
        imported = importlib.import_module(module)
        success, res = imported.main(APIClient.getInstance())
        if success:
            tk.messagebox.showinfo("Script finished", f"Script {script_name} finished.\n{res}")
        else:
            tk.messagebox.showwarning("Script failed", f"Script {script_name} failed.\n{res}")

    def openPathForUser(self):
        selection = self.treevw.selection()
        if selection:
            folder = os.path.join(self.getScriptsDir(), selection[0])
        else:
            folder = self.getScriptsDir()
        Utils.openPathForUser(folder)
예제 #10
0
파일: profs.py 프로젝트: waflia/linux_audit
    def __init__(self, master, main_path=''):
        self.main_path = main_path
        self.master = master
        self.modules_config = {}  #{module_name : }
        self.modules = {}

        self.fio = ''
        self.org = ''

        #Профили аудита
        self.profiles = {}
        self.current_profile_options = {}

        #Левый фрейм включает данные об аудиторе и о существующих профилях
        leftFrame = ttk.Frame(master)
        self.auditor_Frame = ttk.LabelFrame(leftFrame, text='Данные аудитора')
        self.profiles_Frame = VerticalScrolledFrame(leftFrame,
                                                    text='Профили аудита')

        #Правый фрейм включает редактор текущего профиля и кнопку запуска аудита
        rightFrame = ttk.Frame(master)
        self.current_Frame = ttk.LabelFrame(rightFrame, text='Текущий профиль')
        self.btn_Frame = ttk.Frame(rightFrame)

        #Область данных об аудиторе
        fio_Label = ttk.Label(self.auditor_Frame, text='ФИО')
        self.fio_Entry = ttk.Entry(self.auditor_Frame, font=16, width=30)
        self.fio_Label = ttk.Label(self.auditor_Frame, font=16, width=30)
        org_Label = ttk.Label(self.auditor_Frame, text='Организация')
        self.org_Entry = ttk.Entry(self.auditor_Frame, font=16, width=30)
        self.org_Label = ttk.Label(self.auditor_Frame, font=16, width=30)
        self.fio_OK_btn = ttk.Button(self.auditor_Frame,
                                     text='OK',
                                     width=5,
                                     command=self.accept_auditor)

        fio_Label.grid(row=1, column=0, sticky='new', padx=10)
        self.fio_Entry.grid(row=2, column=0, sticky='nsew', padx=10)
        org_Label.grid(row=3, column=0, sticky='new', padx=10)
        self.org_Entry.grid(row=4, column=0, sticky='nsew', padx=10)
        self.fio_OK_btn.grid(row=5, column=0, sticky='se', padx=10)

        self.profileView = CheckboxTreeview(self.current_Frame)
        self.save_audit_btn = ttk.Button(self.btn_Frame,
                                         text='Сохранить профиль',
                                         command=self.save_btn_click)
        self.run_audit_btn = ttk.Button(self.btn_Frame,
                                        text='Запустить аудит',
                                        command=self.run_audit)

        self.ysb = ttk.Scrollbar(self.current_Frame,
                                 orient='vertical',
                                 command=self.profileView.yview)
        self.profileView.configure(yscroll=self.ysb.set)
        ttk.Style().configure('Vertical.TScrollbar',
                              troughcolor='#f6f4f2',
                              relief=tk.GROOVE)
        ttk.Style().configure('Treeview', background="#ffffff")
        ttk.Style().configure('Frame', background="#f6f4f2")

        #Размещения на фреймах
        leftFrame.pack(side=tk.LEFT, anchor='nw', fill=tk.Y)
        rightFrame.pack(side=tk.LEFT, anchor='nw', expand=1, fill=tk.BOTH)

        self.auditor_Frame.pack(side=tk.TOP,
                                anchor='nw',
                                padx=5,
                                pady=5,
                                fill=tk.X)
        self.profiles_Frame.pack(side=tk.TOP,
                                 anchor='sw',
                                 padx=5,
                                 pady=10,
                                 fill=tk.BOTH,
                                 expand=1)

        self.current_Frame.pack(side=tk.TOP,
                                anchor='nw',
                                padx=5,
                                pady=5,
                                fill=tk.BOTH,
                                expand=1)
        self.btn_Frame.pack(side=tk.TOP, anchor='nw', fill=tk.X)

        self.ysb.pack(side=tk.RIGHT, anchor='n', fill=tk.Y)
        self.profileView.pack(side=tk.TOP, anchor='nw', fill=tk.BOTH, expand=1)
        self.save_audit_btn.pack(side=tk.LEFT, anchor='sw', padx=5, pady=5)
        self.run_audit_btn.pack(side=tk.LEFT,
                                anchor='se',
                                padx=5,
                                pady=5,
                                fill=tk.X,
                                expand=1)

        self.auditor_Frame.grid_rowconfigure(2, minsize=30)
        self.loadProfiles()
        self.profileView.bind("<Button-1>", self.check_uncheck_item, True)
예제 #11
0
파일: profs.py 프로젝트: waflia/linux_audit
class main_Tab:
    def __init__(self, master, main_path=''):
        self.main_path = main_path
        self.master = master
        self.modules_config = {}  #{module_name : }
        self.modules = {}

        self.fio = ''
        self.org = ''

        #Профили аудита
        self.profiles = {}
        self.current_profile_options = {}

        #Левый фрейм включает данные об аудиторе и о существующих профилях
        leftFrame = ttk.Frame(master)
        self.auditor_Frame = ttk.LabelFrame(leftFrame, text='Данные аудитора')
        self.profiles_Frame = VerticalScrolledFrame(leftFrame,
                                                    text='Профили аудита')

        #Правый фрейм включает редактор текущего профиля и кнопку запуска аудита
        rightFrame = ttk.Frame(master)
        self.current_Frame = ttk.LabelFrame(rightFrame, text='Текущий профиль')
        self.btn_Frame = ttk.Frame(rightFrame)

        #Область данных об аудиторе
        fio_Label = ttk.Label(self.auditor_Frame, text='ФИО')
        self.fio_Entry = ttk.Entry(self.auditor_Frame, font=16, width=30)
        self.fio_Label = ttk.Label(self.auditor_Frame, font=16, width=30)
        org_Label = ttk.Label(self.auditor_Frame, text='Организация')
        self.org_Entry = ttk.Entry(self.auditor_Frame, font=16, width=30)
        self.org_Label = ttk.Label(self.auditor_Frame, font=16, width=30)
        self.fio_OK_btn = ttk.Button(self.auditor_Frame,
                                     text='OK',
                                     width=5,
                                     command=self.accept_auditor)

        fio_Label.grid(row=1, column=0, sticky='new', padx=10)
        self.fio_Entry.grid(row=2, column=0, sticky='nsew', padx=10)
        org_Label.grid(row=3, column=0, sticky='new', padx=10)
        self.org_Entry.grid(row=4, column=0, sticky='nsew', padx=10)
        self.fio_OK_btn.grid(row=5, column=0, sticky='se', padx=10)

        self.profileView = CheckboxTreeview(self.current_Frame)
        self.save_audit_btn = ttk.Button(self.btn_Frame,
                                         text='Сохранить профиль',
                                         command=self.save_btn_click)
        self.run_audit_btn = ttk.Button(self.btn_Frame,
                                        text='Запустить аудит',
                                        command=self.run_audit)

        self.ysb = ttk.Scrollbar(self.current_Frame,
                                 orient='vertical',
                                 command=self.profileView.yview)
        self.profileView.configure(yscroll=self.ysb.set)
        ttk.Style().configure('Vertical.TScrollbar',
                              troughcolor='#f6f4f2',
                              relief=tk.GROOVE)
        ttk.Style().configure('Treeview', background="#ffffff")
        ttk.Style().configure('Frame', background="#f6f4f2")

        #Размещения на фреймах
        leftFrame.pack(side=tk.LEFT, anchor='nw', fill=tk.Y)
        rightFrame.pack(side=tk.LEFT, anchor='nw', expand=1, fill=tk.BOTH)

        self.auditor_Frame.pack(side=tk.TOP,
                                anchor='nw',
                                padx=5,
                                pady=5,
                                fill=tk.X)
        self.profiles_Frame.pack(side=tk.TOP,
                                 anchor='sw',
                                 padx=5,
                                 pady=10,
                                 fill=tk.BOTH,
                                 expand=1)

        self.current_Frame.pack(side=tk.TOP,
                                anchor='nw',
                                padx=5,
                                pady=5,
                                fill=tk.BOTH,
                                expand=1)
        self.btn_Frame.pack(side=tk.TOP, anchor='nw', fill=tk.X)

        self.ysb.pack(side=tk.RIGHT, anchor='n', fill=tk.Y)
        self.profileView.pack(side=tk.TOP, anchor='nw', fill=tk.BOTH, expand=1)
        self.save_audit_btn.pack(side=tk.LEFT, anchor='sw', padx=5, pady=5)
        self.run_audit_btn.pack(side=tk.LEFT,
                                anchor='se',
                                padx=5,
                                pady=5,
                                fill=tk.X,
                                expand=1)

        self.auditor_Frame.grid_rowconfigure(2, minsize=30)
        self.loadProfiles()
        self.profileView.bind("<Button-1>", self.check_uncheck_item, True)

    def run_audit(self):
        for tab_name, tab in self.modules.items():
            tab.run_audit()

    def sync_vars(self):
        for tab_name, tab in self.modules.items():
            if type(self.current_profile_options[tab_name][1]) != type({}):
                i = 0
                for var in tab.vars:
                    var.set(self.current_profile_options[tab_name][1][i])
                    i += 1
            else:
                i = len(tab.vars) - 1
                for second_tab_name, second_tab in self.current_profile_options[
                        tab_name][1].items():
                    for j in range(len(second_tab[1]) - 1, -1, -1):
                        tab.vars[i].set(second_tab[1][j])
                        i -= 1

    def accept_auditor(self):
        if self.fio_OK_btn.cget('text') == 'OK':
            self.fio = self.fio_Entry.get()
            self.org = self.org_Entry.get()

            self.fio_OK_btn.configure(text='Изменить', width=10)

            self.fio_Entry.grid_remove()
            self.org_Entry.grid_remove()

            self.fio_Label.configure(text=self.fio)
            self.org_Label.configure(text=self.org)
            self.fio_Label.grid(row=2, column=0, sticky='nsew', padx=10)
            self.org_Label.grid(row=4, column=0, sticky='nsew', padx=10)
        else:
            self.fio_OK_btn.configure(text='OK', width=5)
            self.fio_Entry.grid()
            self.org_Entry.grid()

            self.fio_Label.grid_remove()
            self.org_Label.grid_remove()

    def loadProfiles(self):
        for child in self.profiles_Frame.interior.winfo_children():
            child.destroy()
        #self.profiles_Frame.pack(side=tk.TOP, anchor='sw', padx=5, pady = 10, fill=tk.BOTH, expand=1)
        try:
            with open(self.main_path + '/profiles.json') as file:
                self.profiles = json.load(file)
        except:
            with open(self.main_path + '/profiles.json', 'w') as file:
                json.dump(self.profiles, file)

        prof_count = len(self.profiles)
        self.var = tk.IntVar()
        for i in range(prof_count):
            tk.Radiobutton(self.profiles_Frame.interior,
                           variable=self.var,
                           value=i,
                           indicator=0,
                           height=3,
                           text=list(self.profiles.keys())[i],
                           selectcolor="#f19572",
                           activebackground="#f19572",
                           command=self.changeCurrentProfile).pack(side=tk.TOP,
                                                                   anchor='nw',
                                                                   fill=tk.X,
                                                                   padx=5,
                                                                   pady=2)

    def dumpProfiles(self):
        with open(self.main_path + '/profiles.json', 'w') as file:
            json.dump(self.profiles, file)

    def changeCurrentProfile(self):
        currentProfileName = list(self.profiles.keys())[self.var.get()]
        self.current_profile_options = copy.deepcopy(
            self.profiles[currentProfileName])
        self.profileView.heading('#0',
                                 text=list(
                                     self.profiles.keys())[self.var.get()],
                                 anchor='w')
        self.initTree()
        self.sync_vars()
        #self.profiles_Label.configure(text=self.var.get())

    def save_btn_click(self):
        self.saveDialog = tk.Toplevel()
        save_frame = ttk.Frame(self.saveDialog)
        self.saveDialog.focus_set()

        width = self.master.winfo_screenwidth() // 5 + 96
        height = self.master.winfo_screenheight() // 5
        dw = (self.master.winfo_screenwidth() - width) // 2
        dh = (self.master.winfo_screenheight() - height) // 2
        self.saveDialog.geometry('{}x{}+{}+{}'.format(width, height, dw, dh))

        self.saveDialog.resizable(False, False)
        self.saveDialog.title('Сохранение профиля')

        # Настройка виджетов в окне ввода пароля
        save_Label = ttk.Label(save_frame, text='Названия профиля')
        self.save_Entry = ttk.Entry(save_frame, font=16)
        save_Btn = ttk.Button(save_frame, text='Сохранить', width=15)

        self.save_Entry.bind('<Return>', self.save_click)
        save_Btn.bind('<Button-1>', self.save_click)

        save_Label.grid(row=1, column=0)
        self.save_Entry.grid(row=2, column=0, padx=10, sticky='nsew')
        save_Btn.grid(row=3, column=0, padx=10, pady=20, sticky='e')

        save_frame.pack(fill=tk.BOTH)
        save_frame.grid_rowconfigure(1, minsize=height // 3)
        save_frame.grid_rowconfigure(2, minsize=30)
        save_frame.grid_columnconfigure(0, minsize=width)
        self.save_Entry.focus_set()

    def save_click(self, event):
        """Функция-обработчик нажатия кнопки """
        profile_name = self.save_Entry.get()
        self.profiles[profile_name] = self.current_profile_options
        self.dumpProfiles()
        self.loadProfiles()
        self.saveDialog.destroy()
        self.initTree()

    def initTree(self):
        if self.current_profile_options == {}:
            self.current_profile_options = dict(
                self.profiles["Профиль по умолчанию"])

        for (key, value) in self.current_profile_options.items():
            if self.modules_config.__contains__(key):
                if not self.profileView.exists(key):
                    self.profileView.insert("", "end", key, text=key)

                self.profileView.change_state(key, value[0])
                value = value[1]

                if type(value) == type("1"):
                    i = 0
                    for func_key in self.modules_config[key][0].keys():
                        func_key = func_key.replace('\n', ' ')

                        if not self.profileView.exists(key + func_key + "_" +
                                                       str(i)):
                            self.profileView.insert(key,
                                                    "end",
                                                    key + func_key + "_" +
                                                    str(i),
                                                    text=func_key)

                        if value[i] == '0':
                            self.profileView.change_state(
                                key + func_key + "_" + str(i), 'unchecked')
                        if value[i] == '1':
                            self.profileView.change_state(
                                key + func_key + "_" + str(i), 'checked')
                        i += 1
                else:
                    j = 0
                    for (second_key, second_value) in dict(value).items():

                        if not self.profileView.exists(second_key):
                            self.profileView.insert(key,
                                                    "end",
                                                    second_key,
                                                    text=second_key)

                        self.profileView.change_state(second_key,
                                                      second_value[0])
                        second_value = second_value[1]

                        if type(value[second_key][1]) == type("1"):
                            i = 0
                            for func_key in self.modules_config[key][0][
                                    j].keys():
                                func_key = func_key.replace('\n', ' ')

                                if not self.profileView.exists(second_key +
                                                               func_key + "_" +
                                                               str(i)):
                                    self.profileView.insert(
                                        second_key,
                                        "end",
                                        second_key + func_key + "_" + str(i),
                                        text=func_key)

                                if value[second_key][1][i] == '0':
                                    self.profileView.change_state(
                                        second_key + func_key + "_" + str(i),
                                        'unchecked')
                                if value[second_key][1][i] == '1':
                                    self.profileView.change_state(
                                        second_key + func_key + "_" + str(i),
                                        'checked')
                                i += 1
                        j += 1

    def check_uncheck_item(self, event):
        x, y, widget = event.x, event.y, event.widget
        elem = widget.identify("element", x, y)
        if "image" in elem:
            # a box was clicked
            item = self.profileView.identify_row(y)
            children = self.profileView.get_children(item)
            parents = []
            parent = widget.parent(item)
            i = 0
            while parent != '':
                parents.append(parent)
                parent = widget.parent(parent)
            if parents and children == ():
                tag = self.profileView.item(parents[-1], "tags")
                self.current_profile_options[parents[-1]][0] = tag[0]
                if len(parents) == 2:
                    tag = self.profileView.item(parents[0], "tags")
                    self.current_profile_options[parents[-1]][1][
                        parents[-2]][0] = tag[0]
                    tag = self.profileView.item(item, "tags")

                    i = int(item.split('_')[1])
                    varL = self.current_profile_options[parents[-1]][1][
                        parents[-2]][1][0:i]
                    varR = self.current_profile_options[parents[-1]][1][
                        parents[-2]][1][i + 1:]

                    if "checked" in tag:
                        self.current_profile_options[parents[-1]][1][
                            parents[-2]][1] = varL + '1' + varR
                    else:
                        self.current_profile_options[parents[-1]][1][
                            parents[-2]][1] = varL + '0' + varR
                else:
                    tag = self.profileView.item(item, "tags")

                    i = int(item.split('_')[1])
                    varL = self.current_profile_options[parents[-1]][1][0:i]
                    varR = self.current_profile_options[parents[-1]][1][i + 1:]

                    if "checked" in tag:
                        self.current_profile_options[
                            parents[-1]][1] = varL + '1' + varR
                    else:
                        self.current_profile_options[
                            parents[-1]][1] = varL + '0' + varR
            else:
                tag = self.profileView.item(item, "tags")
                self.current_profile_options[item][0] = tag[0]
                profile_1 = ''
                for child in self.profileView.get_children(item):
                    children = self.profileView.get_children(child)
                    if children != ():
                        tag = self.profileView.item(child, "tags")
                        self.current_profile_options[item][1][child][0] = tag[
                            0]
                        profile = ''
                        for s_child in self.profileView.get_children(child):
                            tag = self.profileView.item(s_child, "tags")
                            if 'checked' in tag:
                                profile += '1'
                            else:
                                profile += '0'
                        self.current_profile_options[item][1][child][
                            1] = profile
                    else:
                        tag = self.profileView.item(child, "tags")
                        if 'checked' in tag:
                            profile_1 += '1'
                        else:
                            profile_1 += '0'
                        self.current_profile_options[item][1] = profile_1
        self.sync_vars()
예제 #12
0
from ttkwidgets import CheckboxTreeview
import tkinter as tk
import tkinter.ttk as ttk
from tkinter.font import Font
import ttkwidgets as twk

root = tk.Tk()
root.geometry('500x500')
root.title("Checkbox example")

f1 = tk.Frame(root, width=490, height=490)
f1.pack()

can = tk.Canvas(f1)

tree = CheckboxTreeview(can)
tree.column('#0', minwidth=350, stretch=True)
tree.insert("", "end", "1", text="1" + '2')

tree.insert("1", "end", "11", text="11")
tree.insert("1",
            "end",
            "12",
            text="Anantha" + "kumar" + 'Kondra' + 'Anantha Kumar Kondra')
tree.insert("11",
            "end",
            "111",
            text="Anantha" + "kumar" + 'Kondra' + 'Anantha Kumar Kondra')

tree.insert("",
            "end",
예제 #13
0
def Main():
    window = tkinter.Tk()
    window.title('Security Checker')  # Title
    window.geometry('500x350+450+200')  # Resolution
    window['padx'] = 8
    # window.iconbitmap(default="Appwheel.ico")  # App icon
    title_font = tkfont.Font(family='Arial', size=10,
                             weight="bold")  # Fonts within the App
    label1 = ttk.Label(text="Check the boxes:",
                       font=title_font)  # Writings within the App
    label1.grid(row=0, column=0, sticky="nw", pady=8)

    window.grid_columnconfigure(0, weight=1)
    window.grid_columnconfigure(1, weight=1)
    window.grid_columnconfigure(2, weight=3)
    window.grid_columnconfigure(3, weight=2)
    window.grid_columnconfigure(4, weight=2)
    window.grid_rowconfigure(0, weight=1)
    window.grid_rowconfigure(1, weight=10)
    window.grid_rowconfigure(2, weight=2)
    window.grid_rowconfigure(3, weight=3)
    window.grid_rowconfigure(4, weight=3)

    tree = CheckboxTreeview  # Variable tree equals tree view
    # Edit dictionaries as you like
    # Dict #1
    cisco = {
        1: "enable secret",
        2: "aaa new-model",
        3: "service-password encryption",
        4: "ip ssh version 2",
        5: "motd",
        6: "no logging console",
        7: "no logging monitor",
        8: "vtp password"
    }
    # Dict 2
    smbv1_patch = {
        100: "KB4012598",
        101: "KB4012212",
        102: "KB4012215",
        103: "KB4012213",
        104: "KB4012216",
        105: "KB4012214",
        106: "KB4012217",
        107: "KB4012606",
        108: "KB4013198",
        109: "KB4013429"
    }

    # What should not be present in a configuration files
    should_not_be = [
        "enable password", "snmp-server community public",
        "transport input telnet", "EnableSMB1Protocol              : True"
    ]

    scrollbar1 = ttk.Scrollbar(window, orient="vertical",
                               command=tree.yview)  # Scroll bar
    scrollbar1.grid(row=1, column=6, sticky='nse')

    tree = CheckboxTreeview(yscrollcommand=scrollbar1)
    tree.grid(column=0, columnspan=6, row=1, sticky="news")  # Tree position

    tree.insert("", "end", "1", text="1. CISCO Hardening")
    tree.insert("1", "end", "sub0", text="1.1 Generic configs")
    tree.insert("sub0", "end", cisco[1], text="1.1.1 Password Hash")
    tree.insert("sub0", "end", cisco[3], text="1.1.2 Password Encryption")
    tree.insert("sub0", "end", cisco[2], text="1.1.3 AAA configuration")
    tree.insert("sub0", "end", cisco[4], text="1.1.4 SSH version 2")
    tree.insert("sub0", "end", cisco[5], text="1.1.5 MOTD")
    tree.insert("sub0", "end", cisco[8], text="1.1.6 VTP Password")
    tree.insert("sub0", "end", cisco[6], text="1.1.7 No logging console")
    tree.insert("sub0", "end", cisco[7], text="1.1.8 No logging monitor")

    tree.insert("", "end", "2", text="2. Microsoft SMBv1 Patching Check")
    tree.insert("2",
                "end",
                smbv1_patch[100],
                text="2.1 Windows Vista & Server 2008 (KB4012598)")
    tree.insert("2", "end", "sub10", text="2.2 Windows 7 & Server 2008 R2")
    tree.insert("sub10", "end", smbv1_patch[101], text="2.2 KB4012212")
    tree.insert("sub10", "end", smbv1_patch[102], text="2.3 KB4012215")

    tree.insert("2",
                "end",
                "sub11",
                text="2.4 Windows 8.1 & Server 2012 & 2012 R2")
    tree.insert("sub11", "end", smbv1_patch[103], text="2.4 KB4012213")
    tree.insert("sub11", "end", smbv1_patch[104], text="2.5 KB4012216")
    tree.insert("sub11", "end", smbv1_patch[105], text="2.6 KB4012214")
    tree.insert("sub11", "end", smbv1_patch[106], text="2.7 KB4012217")

    tree.insert("2", "end", "sub12", text="2.8 Windows 10 & Server 2016")
    tree.insert("sub12", "end", smbv1_patch[107], text="2.8 KB4012606")
    tree.insert("sub12", "end", smbv1_patch[108], text="2.7 KB4013198")
    tree.insert("sub12", "end", smbv1_patch[109], text="2.8 KB4013429")

    button2 = ttk.Button(text="Quit", command=sys.exit)  # Close Button
    button2.grid(row=4, column=0, sticky='ws', padx=10,
                 pady=10)  # Close button position

    checked_boxes = list()  # List for appending selected boxes
    lines_in_conf_file = list()  # List for appending the read file
    passed = str('Passed\t\t')
    not_passed = str('Not Passed\t\t')

    def box_select(just):  # Function for appending selected boxes
        checked_boxes.append(tree.get_checked())

    tree.bind('<<TreeviewSelect>>', box_select)

    def file_open():

        if len(tree.get_checked()) > 0:
            readfile = filedialog.askopenfilename(initialdir="/",
                                                  title="Select "
                                                  "configuration"
                                                  " file",
                                                  filetypes=(("txt "
                                                              "files",
                                                              "*.txt *.html"),
                                                             ("all "
                                                              "files", "*.*")))

            try:
                with open(readfile, "r", encoding='utf-8') as opened_file:
                    for i in opened_file:
                        pass
                    encodings = 'utf-8'
            except UnicodeDecodeError:
                encodings = 'utf-16'

            with open(readfile, "r", encoding=encodings) as opened_file:
                for read_line in opened_file:
                    lines_in_conf_file.append(read_line.strip('\n'))
                with open("temp.txt", "a") as conf:  # Opens file --ONCE--
                    for clause in checked_boxes[-1]:  # Loops over selection
                        for line in lines_in_conf_file:  # Loops over conf file
                            if clause in line:  # Checks what equals between loops
                                conf.write("{}".format(passed) + clause +
                                           "\n")  # Writing them into a file
                                break  # Ends IF statement and continues with
                        else:  # a loop on a conf file
                            if clause in should_not_be:  # Checks if selection in not wanted list
                                conf.write(
                                    "{}".format(passed) + clause +
                                    "\n")  # if yes, writes to a file "PASSED"
                            else:
                                conf.write(
                                    "{}".format(not_passed) + clause +
                                    "\n")  # if not, writes to a file "NOT
                                # PASSED"

                checked_configs()

        else:
            pop_up_msg()

    def checked_configs():
        checked = tkinter.Tk()
        # checked.iconbitmap(default="Appwheel.ico")  # App icon
        checked.geometry('650x500+650+300')  # Resolution
        checked.wm_title("Security Checker")

        checked.grid_columnconfigure(0, weight=1)
        checked.grid_columnconfigure(1, weight=1)
        checked.grid_columnconfigure(2, weight=3)
        checked.grid_columnconfigure(3, weight=2)
        checked.grid_columnconfigure(4, weight=2)
        checked.grid_rowconfigure(0, weight=1)
        checked.grid_rowconfigure(1, weight=10)
        checked.grid_rowconfigure(2, weight=2)
        checked.grid_rowconfigure(3, weight=3)
        checked.grid_rowconfigure(4, weight=3)

        label2 = ttk.Label(checked,
                           text='Security check report:',
                           font=title_font)
        label2.grid(row=0, column=0, sticky='ew', padx=10, pady=10)

        button3 = ttk.Button(checked, text="Quit", command=sys.exit)
        button3.grid(row=4, column=0, sticky='ws', padx=10, pady=10)

        def save_report_to_file():
            save_file = filedialog.asksaveasfile(mode='w',
                                                 defaultextension=".txt",
                                                 initialdir="/",
                                                 title="Save "
                                                 "report",
                                                 filetypes=(("txt "
                                                             "files", "*.txt"),
                                                            ("all "
                                                             "files", "*.*")))
            if save_file:
                with open('temp.txt', 'r') as temp_file:
                    for i in temp_file:
                        save_file.write(i)
                    else:
                        return

        button4 = ttk.Button(checked,
                             text="Save to..",
                             command=save_report_to_file)
        button4.grid(row=4, column=5, sticky='es', padx=10, pady=10)

        checked = Text(checked)
        checked.grid(column=0, columnspan=6, row=1, sticky="news")
        checked.insert('1.0', ''.join(open("temp.txt", "r")))

        checked.mainloop()

    def pop_up_msg():
        popup = tkinter.Tk()
        # popup.iconbitmap(default="Appwheel.ico")  # App icon
        popup.wm_title("Security Checker")

        label3 = ttk.Label(
            popup,
            text='Please select at least 1 checkbox to continue',
            font=title_font)
        label3.grid(row=0, column=0, sticky='ew', padx=10, pady=10)

        button5 = ttk.Button(popup, text="Okay", command=popup.destroy)
        button5.grid(row=1, column=0, padx=10, pady=10)

        popup.mainloop()

    button1 = ttk.Button(text="Next", command=file_open)
    button1.grid(row=4, column=5, sticky='es', padx=10,
                 pady=10)  # Open's Browse Button

    window.mainloop()