class MyContainerLabeled(object): def __init__(self, parent, name, del_name, label, x, y, width, height): self.container = LabelFrame(parent, text=label, width=width, height=height) parent.children[name] = parent.children.pop(del_name) self.container.place(x=x, y=y) self.buf_access = self.collect_access() def collect_access(self): result = {} for obj in self.container.children.values(): result[obj] = obj["state"] return result def add_objects(self, objects): self.objects += objects def disable_all(self): for obj in self.objects: obj.object.configure(state="disabled") def enable_all(self): for obj in self.objects: obj.object.configure(state="normal") def restore_state_all(self): for obj in self.objects: obj.object.configure(state=obj.buf_state)
class MainWindow: def __init__(self) -> None: self.Root = Tk() self.App = Frame(self.Root, padding=(5, 2)) self.UpdatesFrame = LabelFrame(self.App, text='Обновление', borderwidth=2, relief='sunken', padding=(5, 2)) self.upd_enabled = BooleanVar() # Флаг обновлений self.upd_unit = StringVar() # Единица измерения времени self.time_units = {Minutes: 'Минут', Hours: 'Часов', Days: 'Дней', Weeks: 'Недель', Months: 'Месяцев'} self.size_units = {Bytes: 'Байт', KBytes: 'Кбайт', MBytes:'Мбайт', GBytes:'Гбайт', TBytes:'Тбайт'} # Список единиц измерения времени self.maxfsize = StringVar() # Максимальный размер файла self.size_unit = StringVar() # Единица измерения информации self.units_amount1 = StringVar() # Количество единиц self.quar = BooleanVar() # False - удалять, True - карантин self.quar_path = StringVar() # Расположение карантина self.rpt_enabled = BooleanVar() # Флаг отправки отчета self.email = StringVar() # Адрес отправки self.passwd = StringVar() # Пароль исходящего ящика self.rpt_unit = StringVar() # Единица измерения времени self.units_amount2 = StringVar() # Количество единиц self.Upd_Label1 = Label(self.UpdatesFrame, text='Проверять обновления антивирусных баз') self.Upd_Checkbutton1 = Checkbutton(self.UpdatesFrame, variable=self.upd_enabled) self.Upd_Label2 = Label(self.UpdatesFrame, text='Частота проверки: каждые') self.Upd_Spinbox1 = Spinbox(self.UpdatesFrame, textvariable=self.units_amount1, from_=1, to=999999999, width=4) self.Upd_OptionMenu1 = OptionMenu(self.UpdatesFrame, self.upd_unit, *self.time_units.values()) self.Upd_Button1 = Button( self.UpdatesFrame, text='Источники антивирусных сигнатур', command=EntryOptionsWindow('AV_SOURCES', self.Root).main) self.ScanFrame = LabelFrame(self.App, text='Сканирование', borderwidth=2, relief='sunken', padding=(5, 2)) self.Scn_Label1 = Label(self.ScanFrame, text='Максимальный размер файла:') self.Scn_Spinbox1 = Spinbox(self.ScanFrame, textvariable=self.maxfsize, from_=0, to=999999999, width=8) self.Quar_Label = Label(self.ScanFrame, text='При обнаружении угрозы') self.Quar_RadButton1 = Radiobutton(self.ScanFrame, text='Удаление', variable=self.quar, value=False) self.Quar_RadButton2 = Radiobutton(self.ScanFrame, text='Карантин', variable=self.quar, value=True) self.Scn_OptionMenu1 = OptionMenu(self.ScanFrame, self.size_unit, *self.size_units.values()) self.Scn_Edit_Targets = Button(self.ScanFrame, text='Цели сканирования', command=EntryOptionsWindow('SCAN_TARGETS', self.Root, select_path=True).main) self.Scn_Edit_Exceptions = Button(self.ScanFrame, text='Исключения', command=EntryOptionsWindow('SCAN_EXCLUDE', self.Root).main) self.Quar_Button1 = Button(self.ScanFrame, text='Расположение карантина', command=lambda: self.quar_path.set(filedialog.askdirectory())) self.ReportFrame = LabelFrame(self.App, text='Отправка отчета', borderwidth=2, relief='sunken', padding=(5, 2)) self.Rpt_Label1 = Label(self.ReportFrame, text='Отправлять отчеты о сканировании') self.Rpt_Checkbutton1 = Checkbutton(self.ReportFrame, variable=self.rpt_enabled) self.Rpt_Label2 = Label(self.ReportFrame, text='Адрес отправки отчетов:') self.Rpt_Entry1 = Entry(self.ReportFrame, textvariable=self.email, width=32) self.Rpt_Label3 = Label(self.ReportFrame, text='Пароль:') self.Rpt_Entry2 = Entry(self.ReportFrame, textvariable=self.passwd, width=32, show='*') self.Rpt_Label4 = Label(self.ReportFrame, text='Частота:') self.Rpt_Spinbox1 = Spinbox(self.ReportFrame, textvariable=self.units_amount2, from_=1, to=999999999, width=4) self.Rpt_OptionMenu1 = OptionMenu(self.ReportFrame, self.rpt_unit, *self.time_units.values()) self.Rpt_Button1 = Button(self.ReportFrame, text='Получатели', command=EntryOptionsWindow('SEND_TO', self.Root).main) self.Buttons = Frame(self.App, padding=(5, 2)) self.Button1 = Button(self.Buttons, text='Готово', command=self.save_conf) self.Button2 = Button(self.Buttons, text='Отмена', command=self.Root.destroy) def main(self) -> None: self.upd_unit.set(self.time_units[type(UPDATE_FREQ)]) self.units_amount1.set(UPDATE_FREQ.value) self.upd_enabled.set(CHECK_FOR_UPDATES) self.Upd_Checkbutton1.configure(command=( lambda: self.__change_state( self.upd_enabled, self.Upd_Label2, self.Upd_Spinbox1, self.Upd_OptionMenu1, self.Upd_Button1) and self.upd_enabled.set(not self.upd_enabled.get()))) self.Rpt_Checkbutton1.configure(command=( lambda: self.__change_state( self.rpt_enabled, self.Rpt_Label2, self.Rpt_Entry1, self.Rpt_Label3, self.Rpt_Entry2, self.Rpt_Label4, self. Rpt_Spinbox1, self.Rpt_OptionMenu1, self.Rpt_Button1) and self.rpt_enabled.set(not self.rpt_enabled.get()))) self.maxfsize.set(MAX_FILE_SIZE.value) self.size_unit.set(self.size_units[type(MAX_FILE_SIZE)]) self.quar.set(REMOVE_THREATS) self.quar_path.set(QUARANTINE_PATH) self.rpt_enabled.set(SEND_SCAN_REPORTS) self.email.set(SEND_FROM) self.passwd.set(SEND_PASSWD) self.rpt_unit.set(self.time_units[type(SEND_FREQ)]) self.units_amount2.set(SEND_FREQ.value) self.App.pack(fill='both', expand=True) center_win(self.Root, '500x500') self.Root.resizable(False, False) self.Root.title('CobraAV Configuration') self.UpdatesFrame.place(y=0, height=150, width=490) self.__change_state(self.upd_enabled, self.Upd_Label2, self.Upd_Spinbox1, self.Upd_OptionMenu1) self.__change_state(self.rpt_enabled, self.Rpt_Label2, self.Rpt_Entry1, self.Rpt_Label3, self.Rpt_Entry2, self.Rpt_Label4, self.Rpt_Spinbox1, self.Rpt_OptionMenu1, self.Rpt_Button1) self.Upd_Label1.place(relx=.01, rely=.05) # Проверять обновления ? self.Upd_Checkbutton1.place(relx=.8, rely=.05) # Да/Нет self.Upd_Label2.place(relx=.01, rely=.3) # Частота проверки self.Upd_Spinbox1.place(relx=.55, rely=.3, width=60) # Количество self.Upd_OptionMenu1.place(relx=.72, rely=.28) # Единицы измерения self.Upd_Button1.place(relx=.01, rely=.65) # Источники сигнатур self.ScanFrame.place(y=150, height=150, width=490) self.Scn_Label1.place(relx=.01, rely=.05) # Максимальный размер файла self.Scn_Spinbox1.place(relx=.55, rely=.05, width=60) # Количество self.Quar_Label.place(relx=.01, rely=.35) self.Quar_RadButton1.place(relx=.52, rely=.35) # Переключатель на удаление угрозы self.Quar_RadButton2.place(relx=.72, rely=.35) # Переключатель на добавление вкарантина угрозы self.Quar_Button1.place(relx=.56, rely=.65) # Расположение карантина self.Scn_OptionMenu1.place(relx=.72, rely=.014) # Единицы измерения self.Scn_Edit_Targets.place(relx=.01, rely=.65) # Цели сканирования self.Scn_Edit_Exceptions.place(relx=.33, rely=.65) # Исключения self.Rpt_Label1.place(relx=.01, rely=.05) # Отправлять отчеты ? self.Rpt_Checkbutton1.place(relx=.8, rely=.05) # Да/Нет self.ReportFrame.place(y=300, height=150, width=490) self.Rpt_Label2.place(relx=.01, rely=.35) # Адрес отправки отчетов: self.Rpt_Entry1.place(relx=.35, rely=.35) # Ввод адреса отправки отчетов self.Rpt_Label3.place(relx=.01, rely=.50) # Пароль: self.Rpt_Entry2.place(relx=.35, rely=.50) # Ввод пароля: self.Rpt_Label4.place(relx=.01, rely=.75) # Частота отправки self.Rpt_Spinbox1.place(relx=.35, rely=.75, width=60) # Количество self.Rpt_OptionMenu1.place(relx=.52, rely=.72) # Единицы измерения self.Rpt_Button1.place(relx=.72, rely=.74) # Получатели self.Buttons.place(y=450, height=50, width=490) self.Button1.place(relx=.62, rely=.2) # Кнопка "Готово" self.Button2.place(relx=.82, rely=.2) # Кнопка "Отмена" self.Root.mainloop() @staticmethod def __change_state(state: BooleanVar, *args: Widget) -> None: for i in args: i.configure(state=('disabled', 'normal')[state.get()]) def save_conf(self) -> None: size_units = {v: k for k, v in self.size_units.items()} time_units = {v: k for k, v in self.time_units.items()} def wrap_list(a: 'list[str]') -> str: return '[' + ', '.join(f"r'{i}'" for i in a) + ']' def wrap_cls(_unit: Variable, amount: Variable) -> str: unit = _unit.get() if unit in size_units: return size_units[unit].__name__ + f'({amount.get()})' elif unit in time_units: return time_units[unit].__name__ + f'({amount.get()})' else: raise NotImplementedError with open(CONF_PATH, 'w') as f: f.write( f"""from libunits import * CHECK_FOR_UPDATES = {int(self.upd_enabled.get())} # Check for updates UPDATE_FREQ = {wrap_cls(self.upd_unit, self.units_amount1)} # Check interval MAX_FILE_SIZE = {wrap_cls(self.size_unit, self.maxfsize)} # Max file size # Antivirus database sources AV_SOURCES = {wrap_list(AV_SOURCES)} # Antivirus database path DB_PATH = r'{DB_PATH}' # On threat: # 0 - quarantine # 1 - remove REMOVE_THREATS = {int(self.quar.get())} # Directories to scan SCAN_TARGETS = {wrap_list(SCAN_TARGETS)} # Exclude from scanning SCAN_EXCLUDE = {wrap_list(SCAN_EXCLUDE)} # quarantine location QUARANTINE_PATH = r'{self.quar_path.get() or QUARANTINE_PATH}' # Send scan reports SEND_SCAN_REPORTS = {int(self.rpt_enabled.get())} # Scan reports frequency SEND_FREQ = {wrap_cls(self.rpt_unit, self.units_amount2)} # Send from this email SEND_FROM = r'{self.email.get()}' # Sender email password SEND_PASSWD = r'{self.passwd.get()}' # Send to these emails SEND_TO = {wrap_list(SEND_TO)} """) self.Root.destroy()
class main(): def __init__(self, tk): self.frame_lgn = Frame(lgn_Screen, width=450, height=750) self.frame_lgn.pack() #Separator self.pane_W = LabelFrame(lgn_Screen, text='Your Credentials', width=300, height=200) self.pane_W.place(x=1, y=10) #Login Entry self.usr_label = Label(lgn_Screen, text="Usuário:") self.usr_label.place(x=22, y=53) self.usr_entry = Entry(lgn_Screen, width=25) self.usr_entry.place(x=72, y=50) #Passowrd Entry self.pw_label = Label(lgn_Screen, text="Senha:") self.pw_label.place(x=30, y=103) self.pw_entry = Entry(lgn_Screen, show="*", width=25) self.pw_entry.place(x=72, y=100) def validate(): usr = str(self.usr_entry.get()) pw = str(self.pw_entry.get()) print(usr) print(pw) #Separator message self.pane_W_Text = LabelFrame(lgn_Screen, text='Your Message:', width=300, height=200) self.pane_W_Text.place(x=1, y=210) #textbox self.tb = Text(lgn_Screen, width=35, height=8, borderwidth=0) self.tb.place(x=7, y=225) #Separator data self.pane_groups = LabelFrame(lgn_Screen, text='Seus Grupos aparecerão aqui:', width=300, height=200) self.pane_groups.place(x=1, y=410) self.tvGroups = Treeview(lgn_Screen) self.tvGroups.place(x=7, y=425, width=287, height=130) #Aviso de Botão fontStyle = tkFont.Font(size=8) self.advcLbl = Label( lgn_Screen, text= "* Aviso: o botão para confirmar o grupo será \nliberado em breve!", font=fontStyle) self.advcLbl.place(x=7, y=610) def conf_Message(): msg = str(self.tb.get('1.0', 'end-1c')) print(msg) from selenium import webdriver from time import sleep from selenium.webdriver.common.keys import Keys url = "https://facebook.com/" d = webdriver.Chrome() d.get(url) sleep(2) target_user = d.find_element_by_xpath('//*[@id="email"]') target_pw = d.find_element_by_xpath('//*[@id="pass"]') target_user.click() sleep(2) target_user.send_keys(str(self.usr_entry.get())) sleep(2) target_pw.send_keys(str(self.pw_entry.get())) sleep(6) log_in = d.find_element_by_xpath('//*[@id="u_0_b"]') sleep(1) log_in.click() sleep(3) webdriver.ActionChains(d).send_keys(Keys.ESCAPE).perform() sleep(4) explore_Group = d.find_element_by_xpath( '//*[@id="navItem_1434659290104689"]/a/div') explore_Group.click() sleep(3) webdriver.ActionChains(d).send_keys(Keys.ESCAPE).perform() sleep(1) try: while True: see_more = d.find_element_by_xpath( "//*[contains(text(), 'Ver mais')]") see_more.click() sleep(2) except: pass sleep(3) groups = d.find_elements_by_class_name('_2yaa') l_groups = [] for g_names in groups: l_groups.append(str(g_names.text)) print(l_groups) group_index = [] counter = 0 for j in l_groups[:-1]: if str(j) == 'Descobrir': continue print(str(counter) + " - " + str(j)) counter += 1 self.tvGroups.insert('', 'end', text=j) #selected_Group = "" def confirmGroup(): self.cur = self.tvGroups.focus() self.selectedItem = str(self.tvGroups.item(self.cur)['text']) print(self.selectedItem) openGroup = d.find_element_by_xpath("//*[contains(text(), '" + self.selectedItem + "')]") openGroup.click() sleep(6) postit = d.find_element_by_xpath( "//*[@name='xhpc_message_text']") postit.send_keys(str(self.tb.get('1.0', 'end-1c'))) sleep(5) publish = d.find_element_by_class_name('_332r') publish.click() self.selgroup = Button(lgn_Screen, text="Confirmar", width=10, font='Verdana 8', borderwidth=0, bg='#FFFFFF', fg='#363636', command=confirmGroup) self.selgroup.place(x=175, y=570) self.cnf_Msg = Button(lgn_Screen, text="Confirmar", width=10, font='Verdana 8', borderwidth=0, bg='#FFFFFF', fg='#363636', command=conf_Message) self.cnf_Msg.place(x=175, y=370, height=20)
class UserInterface: def __init__(self): #colours********** self.FG_COLOR = "#ccedd2" self.BACK_COLOR = "#655c56" self.BG_COLOR = '#deebde' self.ORANGE = '#FFCC66' # *** sizing ***** self.width = 1050 self.height = 600 # main window self.ventana = Tk() self.ventana.geometry( str(self.width) + "x" + str(self.height) + "+200+100") self.ventana.config(bg=self.BG_COLOR) self.ventana.resizable(width=False, height=False) self.ventana.title("PY-POST") # fonts ****** self.font_entry = fnt.Font(family="Monospace", size=16) self.font_h6 = fnt.Font(family="San Serif", size=11) # navigator and menu ---------- self.nav_bar = Frame(self.ventana, width=self.width, height=35, bg=self.BACK_COLOR) self.nav_bar.place(x=0, y=0) self.title = Label(self.nav_bar, text="PY-POST", bg=self.BACK_COLOR, fg=self.FG_COLOR) self.title.place(x=50, y=5) self.version_label = Label(self.nav_bar, text="v - 1.1 ", bg=self.BACK_COLOR, fg=self.FG_COLOR) self.version_label.place(x=930, y=5) #---- special vars---------------------- self.despy = 35 self.c_t = StringVar() self.url_var = StringVar() self.status = StringVar() self.length = StringVar() #--- set headers area ----------------- self.frame2 = Frame(self.ventana, width=700, height=220) self.frame2.place(relx=0.05, y=140 + self.despy) self.frame3 = Frame(self.frame2, width=684, height=34, bg=self.BACK_COLOR) self.frame3.place(relx=0.01, y=181) #-- memory panel-------------------- self.frame_memory = LabelFrame(self.ventana, width=250, height=220, text="Recent requests", labelanchor='nw', relief='ridge') self.frame_memory.place(x=780, y=130 + self.despy) self.memory_frame() self.memory_panel() self.create_widgets() self.ventana.mainloop() # ------- errors methods ----------- @staticmethod def error_dialog(msg): messagebox.showerror("Error", msg) #--- widget methods ----------------------------- def memory_frame(self): self.frame_memory = LabelFrame(self.ventana, width=250, height=220, text="Recent requests", labelanchor='n', relief='ridge') self.frame_memory.place(x=780, y=130 + self.despy) def memory_panel(self): self.memory_frame() self.objects = parse_log() for obj in self.objects: b_g = None if self.objects.index(obj) > 7: break if obj['method'] == 'GET': b_g = "#B2E6C7" elif obj['method'] == 'POST': b_g = "#EAE658" elif obj['method'] == 'UPDATE': b_g = "#F5A66F" elif obj['method'] == 'DELETE': b_g = "#F53333" self.recent_button = Button( self.frame_memory, width=35, text="{} - {}".format(obj['method'][:3], obj['url'][:35]), bg=b_g, command=lambda obj=obj: self.set_var_url(obj['url'])) self.recent_button.pack() def save_reg_to_file(self, dat): self.objects.append(dat) def create_widgets(self): self.label_url = Label(self.ventana, text="Url:", bg=self.BG_COLOR, font=self.font_h6) self.label_url.place(relx=0.05, y=50) self.url_bar = Text(self.ventana, width='70', height=1.2) self.url_bar.place(relx=0.05, y=40 + self.despy) self.url_bar.config(font=self.font_entry) self.get_button = Button(self.ventana, text=" GET ", command=lambda: self.send_request("GET")) self.get_button.place(relx=0.05, y=75 + self.despy) self.get_button.config(fg=self.ORANGE, bg=self.BACK_COLOR) self.post_button = Button(self.ventana, text="POST", command=lambda: self.send_request("POST")) self.post_button.place(relx=0.10, y=75 + self.despy) self.post_button.config(fg=self.ORANGE, bg=self.BACK_COLOR) self.update_button = Button( self.ventana, text=" UPDATE ", command=lambda: self.send_request("UPDATE")) self.update_button.place(relx=0.15, y=75 + self.despy) self.update_button.config(fg=self.ORANGE, bg=self.BACK_COLOR) self.delete_button = Button( self.ventana, text=" DELETE ", command=lambda: self.send_request("DELETE")) self.delete_button.place(relx=0.22, y=75 + self.despy) self.delete_button.config(fg=self.ORANGE, bg=self.BACK_COLOR) self.status_widgets() self.content_type_widgets() #---- RESPONSE AREA WIDGETS------------- self.response_area = Text(self.frame2, width='85', height=10, font=self.font_h6, bd=2) self.response_area.place(relx=0.01, y=4) self.save_button = Button(self.ventana, text="EXPORT TO FILE", bg=self.BACK_COLOR, fg=self.ORANGE, command=self.save_to_file) self.save_button.place(relx=0.63, y=365 + self.despy) self.clear_button = Button(self.ventana, text=" CLEAR ", bg=self.BACK_COLOR, fg=self.ORANGE, command=self.clear) self.clear_button.place(relx=0.56, y=365 + self.despy) def set_var_url(self, url): self.url_bar.delete("1.0", "end") self.url_bar.insert("1.0", url) def clear(self): self.response_area.delete("1.0", "end") self.status.set('') self.c_t.set('') self.length.set('') def status_widgets(self): self.status_label = Label(self.ventana, text="Status : ") self.status_label.place(relx=0.07, y=110 + self.despy) self.status_label.config(bg=self.BG_COLOR, font=self.font_h6) self.status_entry = Entry(self.ventana, textvariable=self.status, width=5, font=self.font_h6) self.status_entry.place(relx=0.13, y=110 + self.despy) self.length_label = Label(self.ventana, text="Content Length:", bg=self.BG_COLOR, font=self.font_h6) self.length_label.place(relx=0.55, y=110 + self.despy) self.length_entry = Entry(self.ventana, textvariable=self.length, width=5, font=self.font_h6) self.length_entry.place(relx=0.67, y=110 + self.despy) def content_type_widgets(self): self.content_label = Label(self.ventana, text='Content-Type:') self.content_label.place(relx=0.20, y=110 + self.despy) self.content_label.config(bg=self.BG_COLOR, font=self.font_h6) self.content_entry = Entry(self.ventana, textvariable=self.c_t, width=28, font=self.font_h6) self.content_entry.place(relx=0.30, y=110 + self.despy) #----------------methods ------------------- def send_request(self, method): self.url = self.url_bar.get("1.0", 'end-1c') if method == 'GET': self.response = SendRequest.get(self.url) elif method == 'POST': data = { 'method': 'POST', 'body': { 'title': 'foo', 'body': 'bar', 'userId': 1 }, 'headers': { "Content-type": "application/json; charset=UTF-8" } } jsondata = json.dumps(data) self.response = SendRequest.post(self.url, jsondata) elif method == 'UPDATE': data = self.response_area.get("1.0", 'end-1c') jsondata = json.dumps(data) self.response = SendRequest.update(self.url, jsondata) elif method == 'DELETE': self.response = SendRequest.delete(self.url) if self.response: self.new_reg_memory = { "method": method, "url": self.url, "time": str(datetime.datetime.now()) } save_reg_url(self.new_reg_memory) if self.response == "err1": self.error_dialog("Debe ingresar una url.") else: self.deploy_data(self.response) else: self.response_area.insert( "1.0", "No se pudo establecer conexión con el servidor") self.frame_memory.destroy() self.memory_panel() def deploy_data(self, response): self.clear() self.headers = self.response.headers self.content_type = self.headers['Content-Type'] self.c_t.set(self.content_type) self.status.set(self.response.status_code) text = self.response.content self.response_area.insert("1.0", text.strip()) try: self.length.set(self.response.headers['content-length']) except: self.length.set('N/A') def save_to_file(self): if self.response_area.get("1.0", 'end-1c') == '': self.error_dialog("No hay contenido para guradar.") return my_filetypes = [('all files', '.*'), ('text files', '.txt'), ('web', '.html'), ('directories', '/*/')] answer = filedialog.asksaveasfilename( parent=self.ventana, initialdir=os.getcwd(), title="Seleccione el nombre de archivo y su ubicación: ", filetype=my_filetypes) if answer: f = open(answer, "w") f.write(self.response_area.get("1.0", 'end-1c')) f.close()