DESCRIPTION.rst 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. Source Repository: https://github.com/chrissimpkins/shellescape
  2. Description
  3. -----------
  4. The shellescape Python module defines the ``shellescape.quote()`` function that returns a shell-escaped version of a Python string. This is a backport of the ``shlex.quote()`` function from Python 3.4.3 that makes it accessible to users of Python 3 versions < 3.3 and all Python 2.x versions.
  5. quote(s)
  6. --------
  7. >From the Python documentation:
  8. 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, for cases where you cannot use a list.
  9. This idiom would be unsafe:
  10. .. code-block:: python
  11. >>> filename = 'somefile; rm -rf ~'
  12. >>> command = 'ls -l {}'.format(filename)
  13. >>> print(command) # executed by a shell: boom!
  14. ls -l somefile; rm -rf ~
  15. ``quote()`` lets you plug the security hole:
  16. .. code-block:: python
  17. >>> command = 'ls -l {}'.format(quote(filename))
  18. >>> print(command)
  19. ls -l 'somefile; rm -rf ~'
  20. >>> remote_command = 'ssh home {}'.format(quote(command))
  21. >>> print(remote_command)
  22. ssh home 'ls -l '"'"'somefile; rm -rf ~'"'"''
  23. The quoting is compatible with UNIX shells and with ``shlex.split()``:
  24. .. code-block:: python
  25. >>> remote_command = split(remote_command)
  26. >>> remote_command
  27. ['ssh', 'home', "ls -l 'somefile; rm -rf ~'"]
  28. >>> command = split(remote_command[-1])
  29. >>> command
  30. ['ls', '-l', 'somefile; rm -rf ~']
  31. Usage
  32. -----
  33. Include ``shellescape`` in your project setup.py file ``install_requires`` dependency definition list:
  34. .. code-block:: python
  35. setup(
  36. ...
  37. install_requires=['shellescape'],
  38. ...
  39. )
  40. Then import the ``quote`` function into your module(s) and use it as needed:
  41. .. code-block:: python
  42. #!/usr/bin/env python
  43. # -*- coding: utf-8 -*-
  44. from shellescape import quote
  45. filename = "somefile; rm -rf ~"
  46. escaped_shell_command = 'ls -l {}'.format(quote(filename))
  47. Issue Reporting
  48. ---------------
  49. Issue reporting is available on the `GitHub repository <https://github.com/chrissimpkins/shellescape/issues>`_