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

# Stabilize Reverse Shell TTY

***

Improve basic reverse shell usability by configuring pseudo-terminal settings for interactive command execution.

When you have a basic netcat reverse shell (or similar), it often lacks proper terminal handling for features like `clear`, tab completion, and arrow keys. To stabilize it and get a fully interactive TTY:

One common method involves using `stty` on the listener side and setting the `TERM` variable on the target.

1. In your netcat listener, press `Ctrl+Z` to background the shell process.
2. Enter the following command in your listener's prompt:

   ```bash
   stty raw -echo; fg
   ```

   This command does two things: `stty raw -echo` disables local echoing and processes input character by character, preventing interference from the local terminal. `fg` brings the netcat process back to the foreground.
3. Now inside the newly foregrounded shell, enter:

   ```bash
   reset xterm
   ```
4. Finally, set the `TERM` environment variable:

   ```bash
   export TERM=xterm
   ```

   This sets the terminal type, allowing programs like `vim` and `sudo` to function correctly and enabling features like tab completion, arrow keys, and the `clear` command.

You may also need to get the terminal dimensions from your local machine and set them on the target for some applications to display correctly.\
On your local machine, run:

```bash
stty size
```

This will output the rows and columns, e.g., `24 80`. Then, on the target machine (inside the reverse shell), set the dimensions:

```bash
stty rows <rows> columns <cols>
```

Replace `<rows>` and `<cols>` with the values obtained from `stty size` on your local machine.

Alternative methods to get a TTY include using Python or the `script` command.

Using Python to spawn a PTY:

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

This one-liner can often be executed directly in the initial non-interactive shell.

Using the `script` command:

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

This command records a terminal session and can allocate a PTY. Alternatively, you might use:

```bash
script /dev/null
```

After running `script`, you might need to press `Ctrl+D` or type `exit` to exit the script recording, which leaves you in the interactive shell.

You should now have a much more robust and user-friendly shell environment with features like tab completion and command history working correctly.
