mirror of https://github.com/python/cpython
Expand shlex.quote example (#9723)
This commit is contained in:
parent
8ef771f18f
commit
30e277bf72
|
@ -38,16 +38,33 @@ The :mod:`shlex` module defines the following functions:
|
||||||
.. function:: quote(s)
|
.. function:: quote(s)
|
||||||
|
|
||||||
Return a shell-escaped version of the string *s*. The returned value is a
|
Return a shell-escaped version of the string *s*. The returned value is a
|
||||||
string that can safely be used as one token in a shell command line.
|
string that can safely be used as one token in a shell command line, for
|
||||||
Examples::
|
cases where you cannot use a list.
|
||||||
|
|
||||||
|
This idiom would be unsafe::
|
||||||
|
|
||||||
|
>>> filename = 'somefile; rm -rf ~'
|
||||||
|
>>> command = 'ls -l {}'.format(filename)
|
||||||
|
>>> print(command) # executed by a shell: boom!
|
||||||
|
ls -l somefile; rm -rf ~
|
||||||
|
|
||||||
|
:func:`quote` lets you plug the security hole::
|
||||||
|
|
||||||
>>> filename = 'somefile; rm -rf /home'
|
|
||||||
>>> command = 'ls -l {}'.format(quote(filename))
|
>>> command = 'ls -l {}'.format(quote(filename))
|
||||||
>>> print(command)
|
>>> print(command)
|
||||||
ls -l 'somefile; rm -rf /home'
|
ls -l 'somefile; rm -rf ~'
|
||||||
>>> remote_command = 'ssh home {}'.format(quote(command))
|
>>> remote_command = 'ssh home {}'.format(quote(command))
|
||||||
>>> print(remote_command)
|
>>> print(remote_command)
|
||||||
ssh home 'ls -l '"'"'somefile; rm -rf /home'"'"''
|
ssh home 'ls -l '"'"'somefile; rm -rf ~'"'"''
|
||||||
|
|
||||||
|
The quoting is compatible with UNIX shells and with :func:`split`:
|
||||||
|
|
||||||
|
>>> remote_command = split(remote_command)
|
||||||
|
>>> remote_command
|
||||||
|
['ssh', 'home', "ls -l 'somefile; rm -rf ~'"]
|
||||||
|
>>> command = split(remote_command[-1])
|
||||||
|
>>> command
|
||||||
|
['ls', '-l', 'somefile; rm -rf ~']
|
||||||
|
|
||||||
|
|
||||||
The :mod:`shlex` module defines the following class:
|
The :mod:`shlex` module defines the following class:
|
||||||
|
|
Loading…
Reference in New Issue