name: python-hardener description: > Hardens Python scripts by applying a complete security review, clean-code refactoring, robust error handling, proper logging, and full docstring coverage — then produces a companion Markdown documentation file.
Use this skill whenever the user uploads or references Python files and asks for any of the following (even if they only mention one): - security review, SQL injection check, shell injection, path traversal - error handling, try/except fixes, bare except removal - logging, RotatingFileHandler, proper log setup - clean code, refactoring, meaningful variable names - docstrings, type hints, parameter documentation - code review, code hardening, production-ready script - "fix this script", "improve this code", "make this safe"
Also trigger when the user says things like "review and fix", "make this production-ready", "add proper error handling and logging", or uploads .py files alongside a review request. If multiple Python files are uploaded together, harden all of them.
You are taking one or more Python scripts and producing corrected, hardened versions of those same files — plus a Markdown documentation file — without inventing new filenames or a migration project around them.
<primary-script-name>.md covering
both the security measures applied and how each module works.Do not create .env.example, migration guides, requirements.txt, or any file
not listed above unless the user explicitly asks for it.
Read the entire file before making any changes. Build a mental list of issues across four categories:
% formatting. Fix with allowlist
validation (assert table in frozenset({...})); parameterised queries for values.subprocess call that uses shell=True or joins a
command into a single string. Fix with list-form calls and no shell=True.Path.resolve() and an allowlist check.os.chdir() permanently changes process working directory.
Replace with subprocess.run(["git", "-C", repo_path, ...]) or equivalent.except: — swallows every exception including KeyboardInterrupt,
SystemExit, and MemoryError. Replace with specific types:
json.JSONDecodeError, subprocess.CalledProcessError, subprocess.TimeoutExpired,
OSError, ValueError, etc. Always log the caught exception.pass in exception blocks — hides failures. Add at minimum a
logger.warning(...) or logger.error(...) with the exception detail.with statements or contextmanager.log() function that opens the log file
each time it runs. Configure handlers once (e.g. RotatingFileHandler) and reuse.connect() called in every method, connection never
closed. Wrap in a @contextmanager that calls conn.close() in finally.Path.mkdir(), sqlite3.connect(), or network
calls at import time. Move into main() or __init__().tempfile.mkstemp() then os.replace().Apply every fix from the analysis pass. Additionally:
Logging — Replace print() statements used for operational output and any
hand-rolled file-append logging with Python's logging module:
- Configure once via a setup function (not at module level, not per-call).
- Use RotatingFileHandler (10 MB / 7 backups) for file output and a
StreamHandler for console.
- Read log level from an environment variable, falling back to INFO.
- Log errors with logger.error("...", exc_info=True) or include the exception
string explicitly so the cause is always visible.
Docstrings — Add Google-style docstrings to every public function, method, and class:
def export_csv(self, table: str) -> Optional[Path]:
"""
Exports a table as a CSV file.
Args:
table: Table name — must be in {'documents', 'skills', 'symlinks'}.
Returns:
Path to the generated CSV file, or None if the table is empty.
Raises:
ValueError: If the table name is not in the allowlist.
sqlite3.Error: On database errors.
OSError: On write errors.
"""
Language-specific stubs — If the code generates skeleton files for multiple
programming languages, make sure each language gets its own idiomatic entry point
(not Python def main(): / if __name__ == "__main__": for Perl, Tcl, Shell, etc).
Write a single Markdown file (<primary-script-name>.md) with these sections:
x that does a critical thing)..md..env already exists and is mentioned as the source of truth,
do not create .env.example.except: replaced with specific exception type(s) + loggingos.chdir() — use subprocess ... -C <path> or cwd= argument insteadtempfile + os.replace()) for state/config filesmain() or __init__().md file present and accurate这个 Skill 质量扎实,对 Python 代码的安全漏洞检查全面细致,重构和文档生成指导也很专业。触发逻辑清晰,不会误触发,输出边界控制得当。存在的小问题是版本较新(0.1.0),缺少示例文件,实际使用效果还需要用户自己验证。总体而言是一个实用且靠谱的安全加固工具。