os.system() with imbeded quotes on centos

Chris Rebert clp2 at rebertia.com
Fri Apr 5 19:36:28 EDT 2013


On Fri, Apr 5, 2013 at 3:00 PM, Cameron Simpson <cs at zip.com.au> wrote:
> On 01Apr2013 20:26, John Gordon <gordon at panix.com> wrote:
> | In <0c9717ca-52dd-49ce-8102-e1432883858a at googlegroups.com> cevyne at gmail.com writes:
> | > someip = '192.168.01.01'
> | > var1 = 'lynx -dump http://' + someip + '/cgi-bin/xxxx.log&.submit=+++Go%21+++  > junk'
> |
> | '&' is a special character in shell commands.  You'll need to quote or
> | escape it.
>
> Or better still, use the subprocess module and avoid going via the
> os.system() altogether:
>
>   http://docs.python.org/2/library/subprocess.html#popen-constructor
>
> If you must go via the os.system(), write yourself a generic function
> to quote a string for the shell, and to quote a bunch of strings
> (essentially " ".join( quoted-individual-strings )). And use it
> rigorously.
>
> Anything else is asking for shell injection attacks/errors, just
> as bad as hand constructing SQL statements.
>
> For example, if I must construct a shell command from arbitrary
> strings (like your URL) I use quote() from this:
>
>   https://bitbucket.org/cameron_simpson/css/src/tip/lib/python/cs/sh.py
>
> That code's nothing special, just what I rolled some years ago for
> exactly this purpose.

No need for third-party code, just use the std lib:
http://docs.python.org/2/library/pipes.html#pipes.quote
http://docs.python.org/3/library/shlex.html#shlex.quote

(But yeah, best of all is to just use `subprocess` with shell=False.)

Cheers,
Chris



More information about the Python-list mailing list