Python File Permissions and Ownership
A script that writes a credential needs to get the file mode right, and the obvious way - write it, then chmod it - leaves a window where anybody can read it. This guide covers the mode a new file actually gets and why, the os.open form that has no window, O_EXCL for claiming a file nobody else has, and why asking whether you can read something is worse than trying.
OS and Process Automation Guide 20 of 39 Intermediate
- Control nodeUbuntu 26.04 LTS
- Python3.14.4
- requests2.34.2
- paramiko5.0.0
- TimeAbout 16 min
Nothing here is version-dependent. It is POSIX behaviour that Python exposes directly, and the numbers in the output are this machine's - notably a umask of 002, which is Ubuntu's default for a user with a private group.
- pytest9.1.1
- PyYAML6.0.3
- boto3 / botocore1.43.78
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| RUNNER01 | 192.168.0.27 | Ubuntu 26.04 LTS | Control node - every script in this path runs here | 2 Core | 4 GB | 50 GB |
This guide includes
Use this when a script writes a credential. This matters because writing the file and then fixing its mode leaves a window where anyone could read it - the fix is never to open it wide in the first place.
- seeing what mode a new file gets
- writing a secret with no window where it is readable
- using
O_EXCL, so an existing file cannot be clobbered - asking whether you can read something before trying
Before you start
-
The mode a new file gets
-
Writing a secret without a window
-
O_EXCL, so you cannot clobber an existing file
-
Asking whether you can read something