title: How to securely escape command line arguments for the cmd.exe shell on Windows?
body: <p>Ok, I have a some command wich MUST be executed in <code>shell=True</code> mode.</p>
  
  <p><code>os.system</code> or <code>subprocess.Popen(..., shell=True)</code></p>
  
  <p>And this command contain string substitution like: <code>cmd = "some_secret_command {0}".format(string_from_user)</code></p>
  
  <p>I want escape <code>string_from_user</code> variable to prevent ANY injections.</p>
  
  <p>Simple wrong answers:</p>
  
  <ol>
  <li><strong>Use <code>shlex.quote</code> - incorrect</strong></li>
  </ol>
  
  <p><code>print(shlex.quote('file.txxt; &amp;ls . #'))</code> -> <code>'file.txxt; &amp;ls . #'</code> (injection)</p>
  
  <p>Example:</p>
  
  <pre><code>&gt; python -c "import sys; print(sys.argv[1])" 'file.txxt; &amp;ls . #'
  secret.txt
  secret2.txt
  </code></pre>
  
  <ol start="2">
  <li><strong>Use escape <code>^</code> - incorrect</strong> </li>
  </ol>
  
  <p>Example:</p>
  
  <pre><code>import os
  
  CMD = '''string with spaces'''.replace('', '^').replace('^"', '')
  os.system('python -c "import sys; print(sys.argv[1])" {0}'.format(CMD))
  </code></pre>
  
  <p>Now I can use <code></code> (space) and inject more then one argument.</p>
  
  <ol start="3">
  <li><strong>Use <code>^</code> and <code>"</code> or <code>'</code> - incorrect</strong></li>
  </ol>
  
  <p>Example:</p>
  
  <pre><code>import os
  
  CMD = '''some arg with spaces'''.replace('', '^').replace('^"', '')
  os.system('python -c "import sys; print(sys.argv[1])" "{0}"'.format(CMD))
  </code></pre>
  
  <p>print <code>^s^o^m^e^ ^a^r^g^ ^w^i^t^h^ ^s^p^a^c^e^s^</code></p>
  
  <p>and if <code>'</code></p>
  
  <pre><code>import os
  
  CMD = '''some spaces'''.replace('', '^').replace('^\'', '')
  os.system('python -c "import sys; print(sys.argv[1])" \'{0}\''.format(CMD))
  </code></pre>
  
  <p>print <code>'some</code></p>
  
  <p>I now about <code>shell=False</code> but this is incorrect for me.</p>