Python security means writing and running Python code so it cannot easily be tricked or misused.
This guide is for students, people learning Python and anyone who writes small scripts at work. You do not need to be a full-time developer to be affected: a short script that reads files, uses a password or installs a package can cause real harm if it is careless.
In short
- Most Python risks come in through four doors: packages you install, data from outside, secrets in your code and commands your script runs.
- Anyone can publish a package, so check the name and the project before you install it.
- Never let outside data reach
eval,execorpickle. Use safer options such as JSON. - Keep passwords and keys out of your scripts, and let a free scanner check your code.
What you will learn
- Explain the four main ways a Python script can be misused.
- Spot risky lines, such as a password typed into a script.
- Check a package name before you install it.
- Ask for a simple scan before a script is shared.
- Ready-made code (package)
- code someone else wrote and shared, which you install to save time.
- Shared package shelf (PyPI)
- the main public place where Python packages are published and downloaded.
- Outside data (input)
- anything your script reads that you did not write, such as files, forms or web replies.
What is Python security?
Think of a big shared toolshed. Anyone in the town can put a tool on the shelf, and anyone can take one home.
Python works a lot like that. It comes with many tools built in, and you can add more from a public shelf called PyPI (the Python Package Index). You install them with a program called pip. This is why Python is so quick to learn and use.
Python security is about using that power with care. It covers the packages you add, the data your script reads, the passwords it holds and the commands it runs. Most problems are not clever attacks. They are small shortcuts that leave a door open.
Where the comparison stops working: in a real toolshed, a broken tool usually looks broken. A harmful package can look and work like the real thing while it quietly does something else.
Why does it matter?
Python runs websites, data reports, AI tools and many quick work scripts. A careless script can leak data or give a stranger a way in.
Installing a package is a trust decision. The pip guide says installing can run code from the package, and pip does not check for tampering unless you ask it to.[1]
If you are learning Python
What could happen: you mistype a package name and install a fake copy made to steal files.
Check this: copy package names from the project's own page, not from memory.
If you write scripts at work
What could happen: a script with a password inside is shared on a team drive, and many people can copy it.
Check this: search your scripts for passwords, keys and tokens before you share them.
If you look after data or AI projects
What could happen: a file someone sends you runs hidden code when your script loads it.
Check this: ask what format shared files use, and avoid loading pickle files from others.
What does it look like?
Here is a short, made-up script that a new analyst might write to tidy a sales report. It works, but it has four risky lines.
Example only. All values are made up.
# tidy_report.py (made-up example)
import pickle, subprocess
DB_PASSWORD = "FAKE-password-0000" (1)
data = pickle.load(open(upload, "rb")) (2)
total = eval(form_value) (3)
subprocess.run("zip " + name, shell=True) (4)
# requirements.txt: reqeusts (5)
- In a real file, this line would contain a working database password, typed straight into the script.
- The script opens a pickle file (a Python way of saving objects) that someone else sent.
- The script treats text typed into a form as Python code and runs it.
- The script builds a command for the computer by gluing a file name onto it.
- A misspelt package name. The package the analyst meant is spelt
requests.
Why this is risky: anyone who sees the script can copy the password. A crafted pickle file can run code when it is loaded.[2] eval runs whatever text it is given, so outside text becomes code.[3] A file name with special characters can change the command.[4] And a misspelt name may install a look-alike package.[6]
The safer way: read the password from a secure store or setting, not the script. Load shared data as JSON. Convert numbers with int() or float() instead of eval. Pass commands as a list, without shell=True. Copy package names from the project's own page and pin the exact version.
How does it work?
Each of the four doors has a simple habit that keeps it closed.
- Packages. Check the name, the project page and how active it is before you install. An OpenSSF guide suggests checking whether a similar name is more popular, as a sign of a fake.[6] Write the exact versions you use in a list, called a requirements file. You can also ask pip to check each download against a known fingerprint, called a hash.[1]
- A separate space per project. A virtual environment (a private folder of packages for one project) keeps each project's packages apart from the rest of the computer.[9] It keeps things tidy. It is not designed as a security wall, so still check what you install.
- Outside data. Treat it as untrusted. Python's own manual warns that
evalandexecrun any code they are given, and that pickle data from an untrusted source can run code.[2][3] JSON is a safer format for data from others. - Commands. When a script runs another program, pass the parts as a list. The manual says that if you turn on the shell yourself, it is your job to make sure special characters cannot change the command.[4]
- Secrets. Keep passwords and keys out of the code. When you need a random password or token, use the
secretsmodule, notrandom, which Python's manual says is not designed for security.[5] - A second pair of eyes. A free tool called Bandit looks for common security issues in Python code.[8] Run it, and ask a colleague to read anything you share.


These risks are real. In December 2022, PyTorch, a popular AI library, reported a problem. A harmful package was uploaded to PyPI with the same name as one of its test-build parts. Some users who installed the test builds with pip got the harmful copy, which collected files and settings from their computers.[7] Read our PyTorch torchtriton attack page for the full story.
A worked example
Juno Falk is a new data analyst at a small, fictional travel firm. She is learning Python and has written a script that tidies the weekly bookings report.
Before she shares it with the team, she asks Tomas Erikson, the firm's only developer, to take a quick look.
Tomas opens the script and smiles. "It works, so now let's check the four doors together."
First, packages. Juno's requirements file lists a package she typed from memory. Tomas compares it with the project's own page. The spelling is right, but there is no version number. Juno adds the exact version she tested with.
Next, outside data. The script loads a pickle file that a partner firm emails each week. Tomas explains that a pickle file can run code when it opens. They ask the partner to send a CSV file instead, which the script reads as plain data.
Then, secrets. The database password sits on line three. Tomas moves it into the computer's secure settings, and the script reads it from there. Because the old script was already on the team drive, he also changes the password.
Last, commands. The script zips the report by gluing the file name onto a command. Juno switches to Python's built-in zip tool, so no command is needed at all.
Tomas runs Bandit on the new version. It flags nothing serious. Juno shares the script, and adds the four doors to her own notes for next time.
Myths and mistakes
| What people think | What is true |
|---|---|
| Packages on PyPI have been checked for safety. | Anyone can publish a package. Check the name and the project before you install it.[6] |
| A virtual environment keeps bad code away from my computer. | It keeps packages tidy and separate. It is not designed as a security wall.[9] |
| Pickle is fine because it is built into Python. | Python's manual warns that pickle is not secure for data you do not trust.[2] |
| It is only a small script, so security does not matter. | Small scripts often hold passwords and get shared. The same habits apply. |
The random module is fine for making passwords. | Use the secrets module for passwords and tokens.[5] |
What can I do this week?
- Search your scripts for passwords, keys and tokens, and move any you find.
- Add exact version numbers to your requirements file.
- Look for
eval,exec,pickleandshell=True, and ask if each one is needed. - Run Bandit on one project and read what it finds.
- Set up a virtual environment for each project you work on.
Checklist
- Package names are copied from the project's own page and checked for look-alikes.
- Exact package versions are written in a requirements file.
- Each project has its own virtual environment.
- No outside data reaches
eval,execorpickle. - Commands are passed as a list, without
shell=True. - No passwords, keys or tokens are written in scripts.
- Random passwords and tokens come from the
secretsmodule. - Code is scanned with a tool such as Bandit and read by a second person before it is shared.
Common questions
Is Python a safe language to learn?
Yes. Python is widely used and well documented, and its manual flags its risky features with clear warnings. Like any language, it can be used carelessly. Learning a few habits early, such as checking packages and keeping secrets out of code, makes your scripts much safer.
How can I tell if a Python package is safe?
You cannot be fully sure, but you can lower the risk. Copy the name from the project's own page. Check that it is active and widely used, and look for a similar name that is more popular. Then pin the exact version you tested and update it on purpose.
When is it fine to use eval?
Rarely, and never on outside data. Python's manual warns that eval runs any code it is given. To turn text into a number, use int() or float(). To read simple values such as lists, the manual points to ast.literal_eval, which only accepts plain values.
Where should I keep passwords for my scripts?
Outside the script. Small projects often use environment settings that are not shared with the code. Teams use a secrets manager, which stores secrets locked away and records who reads them. Whichever you use, never commit the real value to a shared folder or Git.
What is a virtual environment for?
It gives each project its own private set of packages. That stops one project's packages clashing with another's, and makes it easy to delete and rebuild. It does not stop a harmful package from doing harm, so the same package checks still apply.
Where next?
Ready for the detail? Read the practitioner guide: Python Security Guide. It goes further into hash-pinned installs, safe package publishing and the coding patterns to ban across a team.
Also useful:
- Secure Coding for Beginners
- Malicious Packages for Beginners
- Command Injection for Beginners
- Bandit Guide
Related NHI Mgmt Group resources: PyPI API Tokens and Trusted Publishing Security Guide · Secrets Management for Beginners · Environment Variables and .env Files
Key terms
- PyPI
- The main public place where Python packages are shared and downloaded.
- Typosquatting
- Publishing a harmful package with a name very close to a popular one, hoping people mistype it.
- Dependency confusion
- Tricking an installer into picking a public package instead of a private one with the same name.
- Virtual environment
- A private folder of packages for one Python project, kept apart from other projects.
- Pickle
- A built-in Python format for saving objects, which can run code when untrusted data is loaded.
- Hard-coding
- Typing a password or key straight into code instead of storing it safely.
- Bandit
- A free tool that scans Python code for common security issues.
Sources and further reading
- Secure installs. pip documentation, Python Packaging Authority. https://pip.pypa.io/en/stable/topics/secure-installs/, accessed 28 Nov 2026.
- pickle: Python object serialization. Python 3 documentation, Python Software Foundation. https://docs.python.org/3/library/pickle.html, accessed 28 Nov 2026.
- Built-in functions: eval() and exec(). Python 3 documentation, Python Software Foundation. https://docs.python.org/3/library/functions.html, accessed 28 Nov 2026.
- subprocess: Subprocess management, Security considerations. Python 3 documentation, Python Software Foundation. https://docs.python.org/3/library/subprocess.html, accessed 28 Nov 2026.
- secrets: Generate secure random numbers for managing secrets. Python 3 documentation, Python Software Foundation. https://docs.python.org/3/library/secrets.html, accessed 28 Nov 2026.
- Concise Guide for Evaluating Open Source Software. OpenSSF Best Practices Working Group. https://best.openssf.org/Concise-Guide-for-Evaluating-Open-Source-Software, accessed 28 Nov 2026.
- Compromised PyTorch-nightly dependency chain between December 25th and December 30th, 2022. PyTorch, 31 December 2022. https://pytorch.org/blog/compromised-nightly-dependency/, accessed 28 Nov 2026.
- Welcome to Bandit. Bandit documentation, PyCQA. https://bandit.readthedocs.io/en/latest/, accessed 28 Nov 2026.
- venv: Creation of virtual environments. Python 3 documentation, Python Software Foundation. https://docs.python.org/3/library/venv.html, accessed 28 Nov 2026.