Shell Escape for Python

3.8.1 · active · verified Sun Apr 12

The `shellescape` Python module provides the `shellescape.quote()` function, which is a backport of Python 3.8's `shlex.quote()` functionality. It safely escapes strings for use as single tokens within shell commands, mitigating shell injection vulnerabilities when executing external commands from Python scripts. The library is currently active, with its latest release `v3.8.1` in January 2020.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to import the `quote` function and use it to escape user-provided input. The escaped string can then be safely embedded as a single token in a shell command string. While `shellescape` facilitates constructing shell command strings, the general best practice for executing external commands in Python is to pass arguments as a list to `subprocess.run()` (which defaults to `shell=False`) to avoid shell interpretation entirely.

from shellescape import quote
import subprocess

user_input = "my file with spaces; evil command"
safe_argument = quote(user_input)

# Best practice: pass arguments as a list to subprocess.run for security (shell=False is default)
# However, shellescape is used when you absolutely need to construct a shell string
# For demonstration, we'll show how to use the escaped string in a shell command string:
command = f"echo {safe_argument}"

print(f"Original input: '{user_input}'")
print(f"Escaped argument: '{safe_argument}'")
print(f"Constructed command: '{command}'")

# Example of safe execution (though direct list is preferred when possible)
# DO NOT use shell=True with unescaped user input.
# If shell=True is necessary, ensure all user-provided tokens are escaped.
# For this example, we demonstrate the output of the escaped string:
# subprocess.run(command, shell=True, check=True)

view raw JSON →