Skip to content

Instantly share code, notes, and snippets.

@SVilgelm
Last active July 22, 2019 13:16
Show Gist options
  • Select an option

  • Save SVilgelm/ea459b4b195cee16c54d882f9f83c020 to your computer and use it in GitHub Desktop.

Select an option

Save SVilgelm/ea459b4b195cee16c54d882f9f83c020 to your computer and use it in GitHub Desktop.

Revisions

  1. SVilgelm revised this gist Jan 16, 2018. 1 changed file with 27 additions and 0 deletions.
    27 changes: 27 additions & 0 deletions examples.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    * <dl>
    <dt>Old code</dt>
    <dd><pre><code>exec_cmd('ping {ip}'.format(ip=ip))</code></pre></dd>
    <dt>Rewritten code</dt>
    <dd><pre><code>exec_cmd(format_cmd('ping {ip}', ip=ip))</code></pre></dd>
    <dt>Examples</dt>
    <dd><pre><code>format_cmd('ping {ip}', ip="$(rm -rf /)")
    $ ping '$(rm -rf /)'
    ping: cannot resolve $(rm -rf /): Unknown host </code></pre>
    </dd>
    <dd><pre><code>format_cmd('ping {ip}', ip='$(rm -rf '/')')
    $ ping '$(rm -rf '"'"'/'"'"')'
    ping: cannot resolve $(rm -rf '/'): Unknown host</code></pre>
    </dd>
    </dl>

    * <dl>
    <dt>Old code</dt>
    <dd><pre><code>exec_cmd("python -c'print(\"{arg}\")'".format(arg=arg))</code></pre></dd>
    <dt>Rewritten code</dt>
    <dd><pre><code>exec_cmd(format_cmd("python -c'import sys; print(sys.argv[1])' {arg}", arg=arg))</code></pre></dd>
    <dt>Examples</dt>
    <dd><pre><code>format_cmd("python -c'import sys; print(sys.argv[1])' {arg}", arg="'$(rm -rf /)'")
    $ python -c'import sys; print(sys.argv[1])' ''"'"'$(rm -rf /)'"'"''
    '$(rm -rf /)'</code></pre>
    </dd>
    </dl>
  2. SVilgelm created this gist Jan 16, 2018.
    9 changes: 9 additions & 0 deletions shell.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,9 @@
    try: # py3
    from shlex import quote # noqa
    except ImportError: # py2
    from pipes import quote # noqa


    def format_cmd(cmd, *args, **kwargs):
    return cmd.format(*[quote(str(i)) for i in args],
    **{k: quote(str(v)) for k, v in kwargs.items()})