It has security issues just when you run the function with arguments taken from users. For example:

import os
def do_clear(command): # Notice command is sent as argument from outside world and hence this makes it vulnerable
    os.system(command)

If the method is called with for example

do_clear('rm -f */*')

Then it is possible that it deletes all the files of current directory. But if the 'clear' command is to be directly used, you do not have to worry about the security issue, as only 'clear' is run in all conditions. So the following function is secure enough.

def do_clear(): # Notice command is not sent as argument from outside world
    os.system('cls' if os.name == 'nt' else 'clear') # This is not risky as os.system takes clear/cls command always.
Answer from Nabin on Stack Overflow
🌐
Python
docs.python.org › 3 › library › os.html
os — Miscellaneous operating system interfaces
February 23, 2026 - To leave one of the ids unchanged, set it to -1. See chown(). As of Python 3.3, this is equivalent to os.chown(fd, uid, gid). Raises an auditing event os.chown with arguments path, uid, gid, dir_fd. Availability: Unix. The function is limited on WASI, see WebAssembly platforms for more information. ... Force write of file with filedescriptor fd to disk. Does not force update of metadata. Availability: Unix. ... This function is not available on MacOS. ... Return system configuration information relevant to an open file.
Discussions

python - Replace os.system with os.popen for security purposes - Stack Overflow
Anything that uses the shell to ... rm -rf / in your shell :). Both os.system and os.popen use the shell. For security, use the subprocess module with shell = False · Either way, both of those functions have been deprecated since Python 2.6... More on stackoverflow.com
🌐 stackoverflow.com
May 20, 2019
angular - Is using os.system('curl ...') in Python truly unsafe, compared to native libraries? - Stack Overflow
If your python script relies on specific behavior from the command, an unexpected variable in the user's environment can break it. If at some point in the future you will need to let the user customize a bit your script behavior you will need to rewrite it from scratch without os.system() or you might have security ... More on stackoverflow.com
🌐 stackoverflow.com
Potential Security Risks of using Python at Work
A few people have given plausible guesses, but the fact is we can't know how to answer this because we don't know where you work, what systems you're trying to install python and what the security requirements of those systems are. There are a million possible reasons the IT people responsible for security might not want a general-purpose programming environment on a given system. Unfortunately, you have to ask them which ones they are actually concerned about. More on reddit.com
🌐 r/learnpython
54
4
January 21, 2025
file access - How does the code example in the python os module documentation create a security hole? - Stack Overflow
Do you know if there is a recommended way (in python) to mitigate this risk? (Or is it as seemingly hopeless as validating file names?) 2018-12-06T13:04:34.67Z+00:00 ... @K.Nielson: I'm not sure. It mostly matters with setuid scripts, which are kind of a security/compatibility mess already, and I'm not sure what the best practices are for such scripts even when the OS ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Readthedocs
python-security.readthedocs.io › security.html
Python Security — Python Security 0.0 documentation
Once an attacker is able the execute arbitrary Python code, the attacker basically gets a full access to the system. Privilege separation can be implemented “outside” Python by putting Python inside a sandbox. Example with bpo-36506 (closed as not a bug): getattr() executes arbitrary code by design, it’s not a vulnerability. CPython doesn’t verify that bytecode is safe. If an attacker is able to execute arbitrary bytecode, we consider that the security of the bytecode is the least important issue: using bytecode, sensitive code can be imported and executed.
🌐
Quora
quora.com › Is-it-still-a-bad-practice-to-use-OS-system-in-Python-if-the-argument-is-a-string-constant-and-not-a-command-taken-from-the-user
Is it still a bad practice to use OS.system in Python if the argument is a string constant and not a command taken from the user? - Quora
If command is a fixed string and truly never contains untrusted input, os.system will work, but prefer subprocess.run for clearer semantics and better error handling. If you rely on shell features, prefer subprocess.run(command, shell=True) but still prefer to minimize shell=True and document why it’s needed. For production code, tests, libraries, and security-conscious contexts, avoid os.system in favor of subprocess + library replacements.
🌐
Aqua Security
aquasec.com › home › application security › python security
Python Security: 6 Common Risks & What You Can Do About Them
July 23, 2024 - User input is passed directly to standard Python functions (system, popen) responsible for executing commands on the system. This allows an attacker to execute commands on the target system. In a development environment, it is common to see detailed debug output, to help developers identify and troubleshoot problems. However, it is important to separate the development environment from the production environment. Debugging information shown on production systems can lead to security issues.
🌐
Aikido
aikido.dev › home › articles › top 10 python security vulnerabilities developers should avoid
Python Security Vulnerabilities | Top Issues
January 29, 2026 - The PyPI security features (like 2FA for maintainers) are improving, but the onus is on users too: don’t install random packages without scrutiny. If possible, review the source of new dependencies (at least a quick scan for obvious malicious patterns like os.system('curl ...')).
Find elsewhere
🌐
Python
peps.python.org › pep-0551
PEP 551 – Security transparency in the Python runtime | peps.python.org
To summarize, defenders have a need to audit specific uses of Python in order to detect abnormal or malicious usage. With PEP 578, the Python runtime gains the ability to provide this. The aim of this PEP is to assist system administrators with deploying a security transparent version of Python that can integrate with their existing auditing and protection systems.
Top answer
1 of 2
2

The objection is entirely legitimate.

Let's say that your command looks like:

def post_result(result_string):
  os.system('curl http://example.com/report-result/%s' % (result_string,))

Now, what happens if you're told to report a result that contains ; rm -rf ~? The shell invoked by os.system() runs curl http://example.com/report-result/, and then it runs a second command of rm -rf ~.

Several naive attempts at fixes don't work.

Consider, for example:

# Adding double quotes should work, right?
# WRONG: ''; rm -rf ~'' doesn't work here, but $(rm -rf ~) still does.
os.system('curl http://example.com/report-result/"%s"' % (result_string,))

# ...so, how about single quotes?
# STILL WRONG: $(rm -rf ~) doesn't work on its own, but result_string="'$(rm -rf ~)'" does.
os.system("curl http://example.com/report-result/'%s'" % (result_string,))

Even if you avoid direct shell injection vulnerabilities, using a shell exposes you to other kinds of bugs.

At startup time, a shell does a number of operations based on filesystem contents and environment variables. If an untrusted user can manipulate your program into setting environment variables of their choice before calling os.system(), they can cause a file named in ENV to have its commands executed; can shadow commands with exported functions, or can cause other mischief. See ShellShock for a well-publicized historical example.

And that's before considering other things that can happen to your data. If you're passing a filename to a shell, but unknown to you it contains whitespace and glob characters, that filename can be split into / replaced with other names.


The official Python documentation warns against shell use.

Quoting a warning from the Python subprocess module documentation, which is also relevant here:

Warning: Executing shell commands that incorporate unsanitized input from an untrusted source makes a program vulnerable to shell injection, a serious security flaw which can result in arbitrary command execution. For this reason, the use of shell=True is strongly discouraged in cases where the command string is constructed from external input:

>>> from subprocess import call
>>> filename = input("What file would you like to display?\n")
What file would you like to display?
non_existent; rm -rf / #
>>> call("cat " + filename, shell=True) # Uh-oh. This will end badly...

shell=False disables all shell based features, but does not suffer from this vulnerability; see the Note in the Popen constructor documentation for helpful hints in getting shell=False to work.

When using shell=True, pipes.quote() can be used to properly escape whitespace and shell metacharacters in strings that are going to be used to construct shell commands.

os.system() has all the same faults as subprocess.Popen(..., shell=True) -- even more faults, since subprocess.Popen() provides a way to pass data out-of-band from code, and so can be used safely.


Native Python libraries don't call shells for work that the Python runtime can do.

Python has a socket library in its standard library interface, which directly invokes operating system and libc calls to create network connections and interact with them. There is no shell involved in these syscalls; arguments are C structs, C strings, etc; so they aren't prone to shell injection vulnerabilities in the same way that os.system() is.

Some Python libraries, like libcurl, may be slightly less native insofar as they use their own C libraries rather than only calling out to the operating system through functions included in the Python runtime itself; even then, though, these OS-level syscalls are at a much lower level than any shell.

2 of 2
1

This answer is entirely correct. But I'd also like to point out to other cases in which you might think that security doesn't matter. E.g. the command you are running is hard-coded or you have 100% control or trust over what is supplied to it. Even it that case using os.system() is wrong. In fact:

  • You have to rely on external tools that might not be present or, even worse, you might have a command with that name, but it doesn't do what you expect it to do. Maybe because it has a different version or maybe because it's a different implementation of that command (e.g. GNUtar != BSDtar). Manging python dependencies will be much more easy and reliable.
  • It is more difficult to handle errors. You only have a return code which is not always enough to understand what is going on. And I hope that your solution to this problem isn't to parse the command output.
  • Environment variables can modify the way a program works unexpectedly. Many programs use environment variables as an alternative to command line or configuration options. If your python script relies on specific behavior from the command, an unexpected variable in the user's environment can break it.
  • If at some point in the future you will need to let the user customize a bit your script behavior you will need to rewrite it from scratch without os.system() or you might have security problems.
🌐
Black Duck
blackduck.com › blog › python-security-best-practices.html
Six Python Security Best Practices for Developers | Black Duck Blog
March 18, 2024 - Take care of all debugging before the system is taken into production. SAST and SCA tools are highly advisable. Coverity SAST tools uncover any development mistakes that lead to vulnerabilities in your proprietary code, and Black Duck SCA checks open source components and their direct or transitive dependencies for any risks they bring into your code. These tests help make sure you get rid of security risks in your code before production. I hope that this overview of Python security best practices gave you some easy tips for developing with Python.
🌐
Avatao
avatao.com › home › python best practices and common security issues
Python best practices and common security issues -
June 12, 2025 - Probably the most naive approach is something like os.system(‘echo ‘ + user_input). Hopefully, you’re familiar with SQL injections and you already know that a string concatenation like this rarely ends well. A malicious actor can easily exploit your application with a payload like this `hello’; cat ‘secret.txt` to read the contents of arbitrary files. Of course, nowadays there are more sophisticated tools and best practices for calling OS commands and running subprocesses.
🌐
Sourcery
sourcery.ai › vulnerabilities › python-lang-security-audit-dangerous-system-call-tainted-env-args
Python Dangerous System Call with Tainted Environment Arguments | Security Vulnerability Database | Sourcery
A critical security vulnerability where user-controlled strings are passed to os.system/os.popen, invoking a shell where metacharacters enable arbitrary command execution. Command injection can execute arbitrary OS commands, read or modify data, and fully compromise the server. ... Sourcery automatically identifies python ...
🌐
SecureFlag
knowledge-base.secureflag.com › vulnerabilities › code_injection › os_command_injection_python.html
OS Command Injection in Python | SecureFlag Security Knowledge Base
August 5, 2025 - Python has native APIs to execute commands. Some of them accept the shell argument that might be set as True to accept the command as a single string. This should be avoided, with commands being passed as a list of arguments, whenever possible. Some methods in the os library only accept the commands argument as single strings and are prone to introducing an injection vulnerability.
🌐
Python
python.org › dev › security
Python Security | Python.org
Subscribe to the mailing list if you'd like to be updated on newly published security advisories. The mailing list has a public archive including all historical advisories sent to the list. There is also an advisory database published to GitHub using the Open Source Vulnerability (OSV) format which can be consumed using automated tooling.
🌐
Cisco Blogs
blogs.cisco.com › cisco blogs › developer › 5 python security traps you need to avoid
5 Python Security Traps You Need to Avoid
March 30, 2022 - It arises from user inputs that are being directly passed in a standard Python function. The lack of input sanitization is usually the reason. ... # -*- coding: utf-8 -*- # example code snippet py_vuln00: Arbitrary Code Execution: compute_user_input = input('\nType something here to compute: ') if not compute_user_input: print ("No input") else: print ("Result: ", eval(compute_user_input)) # 2*2 # __import__("os").system("ls") # __import__('os').system('rm –rf /')
🌐
Medium
medium.com › hackernoon › 10-common-security-gotchas-in-python-and-how-to-avoid-them-e19fbe265e03
10 common security gotchas in Python and how to avoid them | by Anthony Shaw | HackerNoon.com | Medium
July 9, 2018 - This beautiful example found in the popular Python project Ansible. You could provide Ansible Vault with this value as the (valid) YAML. It calls os.system() with the arguments provided in the file.
🌐
Sourcery
sourcery.ai › vulnerabilities › python-flask-security-injection-os-system-injection
Flask Command Injection via os.system() | Security Vulnerability Database | Sourcery
The Flask application uses os.system() or similar functions with user-controlled input, leading to command injection vulnerabilities. Attackers can execute arbitrary system commands on the server, potentially gaining full control of the system, accessing sensitive files, or compromising the entire infrastructure by injecting malicious commands through user input that gets passed to system command execution functions.
🌐
Reddit
reddit.com › r/learnpython › potential security risks of using python at work
r/learnpython on Reddit: Potential Security Risks of using Python at Work
January 21, 2025 -

So I wanted to install Python, download Selenium library on it, and combine it with Webdriver to access web-driven accounting software to automate some stuff; mainly downloading reports from the accounting software since there are tones of reports to download every month, which the software does not have automation function for. I don't want to deal with any data.

Senior director and I went to IT for the request to download Python and they declined; they said there is a security risk.

Does anyone know what potential security risks they are referring to? I don't have cs background so I'm not very sure. And is there a way to mitigate those risks?

🌐
HackerNoon
hackernoon.com › 10-common-security-gotchas-in-python-and-how-to-avoid-them-e19fbe265e03
10 common security gotchas in Python and how to avoid them | HackerNoon
June 16, 2018 - Writing secure code is hard. When you learn a language, a module or a framework, you learn how it supposed to be used. When thinking about security, you need to think about how it can be misused. Python is no exception, even within the standard library there are documented bad practices for ...