objectif
Générer une chaîne sûre pour le shell sans injection.
code minimal
import shlex
arg = "a b; rm -rf /"
q = shlex.quote(arg)
print(" " not in q or q.startswith("'")) # attendu: True
utilisation
import shlex, subprocess, sys
cmd = f"echo {shlex.quote('hello world')}"
cp = subprocess.run(cmd, shell=True, capture_output=True, text=True)
print(cp.stdout.strip() == "hello world")
variante(s) utile(s)
import shlex
print(shlex.quote("simple") == "simple")
notes
- Utilisez toujours une liste d’args avec subprocess; quote est utile pour logs.
- Ne concaténez jamais d’args non échappés avec shell=True.