> 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-0337.md).

# Stabilizing Shell with Python PTY

***

Upgrade a basic, non-interactive shell to a fully interactive TTY shell on Linux systems using Python's `pty` module. This provides features like tab completion, command history, and better handling of interactive programs such as `su`, `sudo`, `vi`, and `ssh`.

The Python `pty` module provides a way to create a pseudoterminal. The `pty.spawn()` function specifically creates a new pseudoterminal and connects the local terminal to the remote one, effectively upgrading the shell.

Execute the following command:

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

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

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

If the terminal display or behavior is still not quite right (e.g., no echoing, weird character output, inability to use Ctrl+C or Ctrl+Z), you often need to adjust the terminal settings. This is because the terminal might be in "cooked" mode, which processes special characters locally, rather than "raw" mode, which passes characters directly without interpretation.

First, background the current shell session using `Ctrl+Z`. Then, run `stty raw -echo` in the original terminal (if available) or a new one connected to the target. This command puts the terminal into raw mode (`raw`) and disables local echoing (`-echo`), allowing the remote shell to handle character processing and echoing. Finally, foreground the shell session you backgrounded (`fg`).

```bash
# After Ctrl+Z
stty raw -echo
# ... then in the same terminal ...
fg
```

You might also need to set the terminal type using the `TERM` environment variable. This is necessary for many interactive programs like `vi`, `vim`, `ssh`, etc., to render correctly.

```bash
export TERM=xterm
```

Sometimes, you can also set the terminal size to match your current window using the `stty rows <num> cols <num>` command.

```bash
stty rows 38 cols 116
```

Besides Python, other scripting languages or tools can also be used to spawn a TTY shell:

Using Perl:

```bash
perl -e 'exec "/bin/sh";'
```

Using Ruby:

```bash
ruby -e 'exec "/bin/sh"'
```

Using the `script` command:

The `script` command makes everything interactive by default. Using `/dev/null` prevents logging output to a file.

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

Or with `sh`:

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

These methods help transform a limited, non-interactive shell into a fully functional TTY, greatly improving usability and enabling the execution of interactive commands and programs.
