PythonIntermediate · Windows, macOS, or Linux; Python 3.12+

Audit likely private-key file modes

Flag POSIX group or other permission bits on likely private-key files without reading contents.

Before you begin

  • Python 3.12 or later.
  • Linux or macOS with POSIX file modes. Filenames are a heuristic; ACLs need separate inspection.
What this script changesRead-only local report. No permissions, accounts, configuration, or input files are changed. Review filenames and metadata before sharing.

Set up your example

  1. Save as security-private-key-modes.py.
  2. Open a terminal in its folder.
  3. Run python "security-private-key-modes.py" --help and prepare the listed input files.

This recipe uses your own local input or creates its own example output. Follow the setup steps below.

Download the ZIP, extract it, and open a terminal inside the extracted folder. The source file is security-private-key-modes.py.

Run the script

Run command
python "security-private-key-modes.py" "~/.ssh"

If your system uses python3 instead of python, use that command for Python examples. Keep paths containing spaces in quotes. Required inputs and optional settings are described in the code and setup steps.

What to expect

A likely key file with mode 0644 is flagged; 0600 has no group/other mode bits.

The complete script

security-private-key-modes.py
#!/usr/bin/env python3
"""Flag POSIX group or other permission bits on likely private-key files without reading contents."""
import argparse
import sys
import json
from pathlib import Path
import os
import stat
import hashlib
import re

def files(root,limit=10000):
    root=root.expanduser().resolve()
    if not root.is_dir():raise ValueError('Input must be an existing directory')
    count=0
    for directory,dirs,names in os.walk(root,followlinks=False):
        dirs[:]=[name for name in dirs if not (Path(directory)/name).is_symlink()]
        for name in names:
            path=Path(directory)/name
            if not path.is_file() or path.is_symlink():continue
            count+=1
            if count>limit:raise ValueError(f'File limit {limit} exceeded; select a smaller directory')
            yield path

def sha(path):
    with path.open('rb') as stream:return hashlib.file_digest(stream,'sha256').hexdigest()

def main():
    parser = argparse.ArgumentParser(description='Flag POSIX group or other permission bits on likely private-key files without reading contents.')
    parser.add_argument('directory',type=Path)
    args = parser.parse_args()
    if os.name!='posix':raise ValueError('POSIX modes are required; use Windows ACL tools on Windows')
    for path in files(args.directory):
        if path.suffix.lower() in {'.pem','.key'} or path.name in {'id_rsa','id_ed25519','id_ecdsa'}:
            mode=stat.S_IMODE(path.stat().st_mode)
            print(json.dumps({'path':str(path),'mode':oct(mode),'group_or_other_access':bool(mode&0o077)}))

if __name__ == '__main__':
    try:
        main()
    except (OSError, ValueError, RuntimeError) as exc:
        print(f'Error: {exc}', file=sys.stderr)
        sys.exit(1)

Open source as plain text · Download source and sample files

How it works

  1. Flag POSIX group or other permission bits on likely private-key files without reading contents.
  2. Arguments are explicit and expected input errors produce a message with a nonzero exit code.
  3. Results reflect your selected local data or the specific endpoint you choose; the example illustrates the result shape.

Make it your own

Adapt the task

Pass the expanded actual SSH path if your shell does not expand quoted ~. Adjust the suffix set for your key naming policy.

Adjust presentation

Edit final print statements or json.dumps indentation to adjust the report layout. Keep input validation and exclusive-create file modes intact.

Change one setting at a time, run it again on sample data, and compare the output. The customization guide walks through this process.

If something goes wrong

An input or dependency is unavailable.

Linux or macOS with POSIX file modes. Filenames are a heuristic; ACLs need separate inspection.

Actual results differ from the example.

Inputs and system state determine values. Review each finding in context; a report is not proof of system health or a complete security assessment.

Reference & next steps

These official references explain the underlying tools. The Scriptage example and guide are original instructional content. See verification notes for what has been checked and the limits of those checks.

Copies a template for your own notes. It does not send anything.