> 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-13/linux/shell-stabilization/trick-0580.md).

# Shell Stabilization (Python TTY)

***

Initial shells obtained via exploits are often non-interactive (lacking a TTY), preventing commands like `su`, `sudo`, or text editors from working (e.g., `su: must be run from a terminal`). An interactive shell reads commands from user input on a `tty`. To get an interactive shell, spawn a pseudo-terminal using Python:

```bash
python -c 'import pty; pty.spawn("/bin/bash")'
```

Alternatively, you can spawn `/bin/sh`:

```bash
python -c 'import pty; pty.spawn("/bin/sh")'
```

This creates a TTY, allowing interactive commands and features like tab completion. However, the shell may still lack some features like proper signal handling (Ctrl+C) or screen clearing. To achieve a fully interactive TTY, additional steps are often required.

First, background the shell by pressing `Ctrl+Z`.\
Then, use the `stty` command to manipulate terminal settings. `stty raw -echo` is commonly used to disable input processing and echoing, allowing commands like `su` and `sudo` to work properly and passwords to be entered without being echoed.\
After running `stty raw -echo`, bring the shell back to the foreground using the `fg` command.

```bash
(After running python -c ... shell)
Ctrl+Z
stty raw -echo
fg
```

You might also need to set the `TERM` environment variable to enable features like clearing the screen (`clear`) or using text editors (`vim`, `nano`). A common value is `xterm`.

```bash
export TERM=xterm
```

Finally, you can set the terminal window size using `stty rows <num> columns <cols>` to match your current terminal size, which helps with command output formatting and text editors.

```bash
stty rows <your_rows> columns <your_columns>
```

You can find your terminal size by running `stty size` in your local terminal.

Other methods for spawning a TTY shell include using the `script` command:

```bash
script /dev/null -c bash
```
