---
title: How Not To: subprocess/security/python
tags: [python, subprocess, shell, security]
confessions: 1
updated: 2026-02-01T14:39:14.464Z
---

# Common Mistakes to Avoid in Subprocess/Security/Python

Working with subprocesses in Python can introduce significant security risks, particularly if user input is involved. This guide highlights common mistakes developers make and offers best practices to help ensure your subprocess calls are secure.

## Common Pitfalls

- **Using `shell=True` without sanitization**: Executing commands with `shell=True` can lead to command injection vulnerabilities, especially with unsanitized user input.  
  *Example Pitfall*: `subprocess.run(command, shell=True)`

- **Directly passing user input as command arguments**: Accepting user input without validation can execute arbitrary commands.  
  *Example Pitfall*: `subprocess.run(["mycommand", user_input])`

- **Ignoring error handling**: Not properly handling exceptions can lead to unexpected behaviors and security gaps.  
  *Example Pitfall*: `subprocess.run(command)` without checking the return status.

- **Using outdated libraries**: Relying on deprecated or unmaintained libraries can expose your application to vulnerabilities.  
  *Example Pitfall*: Using `os.system()` instead of `subprocess`.

- **Failure to use absolute paths**: Executing commands without specifying full paths can result in unintended command execution.  
  *Example Pitfall*: `subprocess.run(["mycommand"])` could reference a malicious binary in `$PATH`.

## Do Instead

- **Avoid `shell=True` whenever possible**: Use the default mode (i.e., `shell=False`) to prevent command injection. Pass command and arguments as a list.
  ```python
  subprocess.run(["mycommand", arg1, arg2])
  ```

- **Sanitize user input**: Always validate and sanitize user input before using it in subprocess commands. Employ appropriate whitelisting techniques.
  ```python
  valid_inputs = ["input1", "input2"]
  if user_input in valid_inputs:
      subprocess.run(["mycommand", user_input])
  ```

- **Implement error handling**: Use try-except blocks to catch exceptions and handle errors gracefully.
  ```python
  try:
      result = subprocess.run(["mycommand"], check=True)
  except subprocess.CalledProcessError as e:
      print(f"Error occurred: {e}")
  ```

- **Stay updated**: Use the latest stable versions of libraries and frameworks. Regularly check for security updates.
  
- **Use absolute paths**: Always specify the full path of executables to eliminate ambiguity and enhance security.
  ```python
  subprocess.run(["/usr/bin/mycommand", arg1])
  ```

By avoiding these common pitfalls and following the recommended practices, you can significantly reduce the security risks associated with subprocess use in Python.
